Can one set multiple properties inside an object literal to the same value?

PitaJ picture PitaJ · Oct 28, 2012 · Viewed 30.3k times · Source

For example, can I do this?:

{ 
   a: b: c: d: 1,
   e: 2,
   geh: function() { alert("Hi!") }
}

EDIT: Is there some way I can avoid doing this?:

{ 
   a: 1,
   b: 1,
   c: 1,
   d: 1,
   e: 2,
   geh: function() { alert("Hi!") }
}

Answer

Pebbl picture Pebbl · Oct 28, 2012

An update to this (in terms of the latest JavaScript abilities) avoiding unwanted defined vars:

{
  let v;
  var obj = {
     "a": (v = 'some value'),
     "b": v,
     "c": v
  };
}

This will mean v won't be defined outside the block, but obj will be.

Original answer

Another way of doing the same thing is:

var v;
var obj = {
     "a": (v = 'some value'),
     "b": v,
     "c": v
};