Shorthand Properties
Object methods in ES5 require the function statement.
// ES5 code
var str = {
sum: function(a, b) { return a + b; },
mult: function(a, b) { return a * b; }
};
console.log( str.sum(5, 5) ); //Output : 10
console.log( str.mult(10, 15) ); //Output : 150
While in ES6, it uses a shorthand technique.
// ES6 code
const str = {
sum(a, b) { return a + b; },
mult(a, b) { return a * b; }
};
console.log( str.sum(5, 5) ); //Output : 10
console.log( str.mult(10, 3) ); //Output : 30
Dynamic Property Keys
Sometimes you need to create an object with a specific property, but the name of that property is not a compile-time constant that you can type literally in your source code. Instead, the property name you need is stored in a variable or is the return value of a function that you invoke.
In ES5, it wasn’t possible to use a variable for a key name, although it could be added after the object had been created.
// ES5 code
var
key1 = 'three',
obj = {
two: 5,
three: 7
};
obj[key1] = 3;
console.log(obj.two); //Output : 5
console.log(obj.three); //Output : 3
// ES6 code
const
key1 = 'one',
obj = {
[key1]: 1,
two: 5,
three: 7
};
// obj.one = 1, obj.two = 2, obj.three = 3
console.log(obj.two); //Output : 5
console.log(obj.three); //Output : 7
Spread Operator
We can copy an array or object using the spread operator.
const str = {
x: 1,
y: 2,
z: 3
};
const { x, ...a } = str;
console.log(x); // Output : 1
console.log(a); // Output : { y: 2, z: 3 }
Destructuring
It’s often necessary to extract a property value from an object into another variable.
// ES6 code
const str = {
one: 'x',
two: 'y',
three: 'z'
};
const { one, two, three } = str;
console.log(one); // Output : x
console.log(two); // Output : y
console.log(three); // Output : z