JavaScript ES6 features: Spread Operator

es6 introduces a new operator called Spread Operrator, which allow us to spread / expand iterable object such as array.

The Spread Operator syntax has 3 dots (…). Spread Operator syntax looks exactly like Rest Parameter syntax, the main difference is Spread Operator unpack an array, while Rest Parameter collects multiple elements and pack them into an array. See Rest Parameter.

Assuming we want to concatenate 2 arrays together:

const asia = ['Japan', 'China', 'India'];
const europe = ['UK', 'France', 'Austria', ...asia];
console.log(europe);
// output: UK, France, Austria, Japan, China, India

Similar to the previous example, we may use the Spread Operator together with push() function:

const asia = ['Japan', 'China', 'India'];
const europe = ['UK', 'France', 'Austria'];
asia.push(...europe);
console.log(asia);
// output: ['Japan', 'China', 'India', 'UK', 'France', 'Austria']

 The Spread Operator only works in-place, like in an argument to a function or in an array literal. The following code will not work:

const world = ...europe;

You may also interested in:

Follow onlyWebPro.com on Facebook now for latest web development tutorials & tips updates!


Posted

in

by

Advertisement