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);
Share
Improve this question
edited Jul 2, 2018 at 21:12
R Balasubramanian
8098 silver badges19 bronze badges
asked Jul 2, 2018 at 20:54
Bryce77Bryce77
3154 silver badges15 bronze badges
1
-
There is no such thing as an "empty" variable. Even if you do
var a;
,a
is implicitly assign the valueundefined
. 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 returnundefined
. – Felix Kling Commented Jul 2, 2018 at 21:05
2 Answers
Reset to default 4var 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.