Shortcut to initialize objects

Here’s a quick and more readable way to initialize objects from other variables.

But, first - how do you normally define objects?

const nums = {};

I mean.. initialize objects - from other variables.

let x = 2;
let y = 4;
const nums = { x: x, y: y };
console.log(nums);
// { x: 2, y: 4 }

You can do the same without using named variables if you like.

let x = 2,
  y = 4;
const nums = { x, y };
console.log(nums);
// { x: 2, y: 4 }

The same holds true for more complex objects as well.

const earth = { position: 3, life: true };
const mercury = { position: 1, life: false };

const planets = { earth, mercury };
console.log(planets);

/* output 
{ earth: { position: 3, life: true },
  mercury: { position: 1, life: false }
}
*/
comments powered by Disqus