
Enhanced object properties
ES6 introduces a concept called array destructuring, which is a way of initializing variables at once. For example, consider the following:
let [x, y] = ['a', 'b'];
Executing the preceding code is the same as doing the following:
let x = 'a'; let y = 'b';
Array destructuring can also be performed to swap values at once without the need to create temp variables, as follows:
[x, y] = [y, x];
The preceding code is the same as the following one:
var temp = x; x = y; y = temp;
This will be very useful when you learn sorting algorithms as these swap values are very common.
There is also another functionality, called property shorthand, which is another way of destructuring objects. For example, consider the following example:
let [x, y] = ['a', 'b']; let obj = { x, y }; console.log(obj); // { x: "a", y: "b" }
The preceding code is the same as doing the following:
var x = 'a'; var y = 'b'; var obj2 = { x: x, y: y }; console.log(obj2); // { x: "a", y: "b" }
The last functionality that we will discuss in this topic is called the shorthand method names. This allows developers to declare functions inside objects as if they were properties. The following is an example:
const hello = { name: 'abcdef', printHello() { console.log('Hello'); } }; console.log(hello.printHello());
The preceding code can also be written as follows:
var hello = { name: 'abcdef', printHello: function printHello() { console.log('Hello'); } }; console.log(hello.printHello());
The three examples presented can be executed at:
- Array destructuring: https://goo.gl/VsLecp
- Variable swap: https://goo.gl/EyFAII
- Property shorthand: https://goo.gl/DKU2PN