Categories
JavaScript Answers

How to automatically add properties to an object that is undefined with JavaScript?

Spread the love

Sometimes, we want to automatically add properties to an object that is undefined with JavaScript.

In this article, we’ll look at how to automatically add properties to an object that is undefined with JavaScript.

How to automatically add properties to an object that is undefined with JavaScript?

To automatically add properties to an object that is undefined with JavaScript, we can use the nullish assignment operator.

For instance, we write

const test = {};
test.hello ??= {};
test.hello.world ??= "Hello";

to create the empty test object.

Then we assign test.hello to an empty object if it doesn’t exist with

test.hello ??= {};

Then if test.hello.world doesn’t exist, we assign it to "Hello" with

test.hello.world ??= "Hello";

Conclusion

To automatically add properties to an object that is undefined with JavaScript, we can use the nullish assignment operator.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.