If I create an object by doing let obj = {}, I can create a new link property by doing obj.link = 'test' and it works.
What if I want instead to create a nested property?
The code below gives an undefined error:
let obj = {}
obj.link.link = 'test'
console.log(obj.link.link)
What's the right way to do this?
You're trying to access link property inside link, which is not there by the time. So you can do below things.
obj = {}
obj.link = {};
obj.link.link = 'test';
console.log(obj.link.link);
console.log(obj);
Or
obj = {}
obj.link = {link: 'test'}
console.log(obj.link.link);
console.log(obj);
You need to have an object to address a property inside of an object.
Toassign use a default object and assign with the value to the last property.
let obj = {};
(obj.link ??= {}).link = 'test';
console.log(obj.link.link);
console.log(obj);