Skip to content Skip to sidebar Skip to footer

What Is The Correct Way To Initialise An Empty Property Of An Object In Javascript

I have an object that with properties, 1 of those properties prop2 will only be initialised later and added to this object when its ready. I want to show it as a property of the ob

Solution 1:

I usually use null for this purpose. It is distinct from undefined (does not exist) and satisfies the requirement that the variable exists but has no value.

Solution 2:

The usual way is to use null.

undefined would work as well, but a) it's longer b) it's not a keyword c) too many people use typeof to test for property existence. It also has a little different notion.

As you said, depending on the expected type you might as well use any other appropriate value. Empty objects or strings are less convential, especially since objects have lots of construction overhead. Do not use them if you don't plan to use (extend) them later.

Post a Comment for "What Is The Correct Way To Initialise An Empty Property Of An Object In Javascript"