Jichao Jichao - 2 months ago 14
Javascript Question

Javascript props assignment without key?

let text = 'how are you';
let foo = {
type : 'foo',
text
};
console.log(foo);


Why the key
text
is auto assigned, is there any reference on such syntax?

Answer

This is a shorter notation in ECMAScript 2015(ES6) Object initializer.

//ES5
var a = "foo", 
    b = 42, 
    c = {};

var o = { 
  a: a,
  b: b,
  c: c
};

//ES6 shorter notation available to achieve the same:  
var o = { a, b, c };
Comments