最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to define empty variable in object literal? - Stack Overflow

programmeradmin0浏览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);

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 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 Commented Jul 2, 2018 at 21:05
Add a ment  | 

2 Answers 2

Reset to default 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
}

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.

发布评论

评论列表(0)

  1. 暂无评论