Bryce77
Bryce77

Reputation: 315

How to define empty variable in object literal?

I am trying to define an empty variable in an object literal but I'm getting an error "Uncaught ReferenceError: a is not defined". Can anyone please help me here? Thanks.

var obj = {
   a,
   b: 1
}

console.log(obj.a);

Upvotes: 0

Views: 3421

Answers (2)

Felix Kling
Felix Kling

Reputation: 816462

FWIW, there is no such thing as an "empty" variable. Even if you do var a;, a is implicitly assigned the value undefined.


Depending on your use case (you are not providing much information), you may not have to define anything at all.

Accessing a non-existing property already returns undefined (which can be considered as "empty"):

var obj = { b: 1 }
console.log(obj.a);

Of course if you want for...in or Object.keys or .hasOwnProperties to include/work for a, then you have to define it, as shown in the other answer;


FYI, { a, b: 1 } does not work because it is equivalent to {a: a, b: 1} i.e. you are trying to assign the value of variable a to property a, but for this to work, variable a has to exist.

Upvotes: 3

Damian Peralta
Damian Peralta

Reputation: 1866

var obj = { a: null, b: 1 }
console.log(obj.a);

Later, you can assign a value to a:

obj.a = 1;

Edit: You can also set the value to undefined, empty string, or any other type:

var obj = { 
  a: null, 
  b: undefined,
  c: '',
  d: NaN
}

Upvotes: 4

Related Questions