0

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 object purely for human readability so that when I look at the code later I will know that it exists and will/can be used.

So my question is what is:

What is the correct way to initialise an empty property of an object in JavaScript

myObject = {
    prop1: 'somevalue',
    prop2: '' <---- ''|null|undefined|false|0|{} what is correct
    }

I am assuming it depends on the type that will be used, and I realise that anything actually works, I am interested in the best practice way.

Fiddler: http://jsfiddle.net/gamelodge/DWCEa/

Andre
  • 2,449
  • 25
  • 24
  • Types doesn't really matter in javascript, as you can change the type at any time by giving the object a value of a certain type etc. so just setting it to an empty string is fine, but it depends on how you intend to use it, I often set properties to false as default when I intend to check them later etc. – adeneo Jul 11 '13 at 23:57

2 Answers2

5

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.

Lior Cohen
  • 8,985
  • 2
  • 29
  • 27
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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks for the link: I like what they say on that link, which will help me remember it -- "undefined is the lack of a type and value, and null is the lack of a value."-- – Andre Jul 12 '13 at 00:43