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);
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);
 
    
     
    
    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
}
 
    
    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.
