0

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);
Bryce77
  • 315
  • 4
  • 15
  • There is no such thing as an "empty" variable. Even if you do `var a;`, `a` is implicitly assign the value `undefined`. Is that what you want for this property? Why do you want to declare an "empty" property in the first place? Accessing a non-existing property will already return `undefined`. – Felix Kling Jul 02 '18 at 21:05

2 Answers2

4
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
}
Damian Peralta
  • 1,846
  • 7
  • 11
  • Thanks for the prompt help Damian. Do I need to assign always NULL for an empty var or is there any other way? – Bryce77 Jul 02 '18 at 20:59
  • 1
    You can have null, undefined, NaN, an empty string, en empty array or a default value of your choice, you just have to put something in there, it can't be `{a:}` – Rainbow Jul 02 '18 at 21:04
  • 1
    you can also use `undefined`, I prefer to use `null`, the difference is very subtle. You can check here: https://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript – Damian Peralta Jul 02 '18 at 21:04
3

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143