My Development Notes


The Spread Operator (…) or the three dots in JavaScript


The Spread Operator in JavaScript simply copies all the elements of an array and outputs them to the console. It is represented by i.e., the three dots.

Let’s understand it better using the simple code below:

const animals1 = ['cat','dog','tiger'];
const animals2 = ['lion','giraffe','hippo'];
const allAnimals = [ ...animals1, ...animals2];
console.log(allAnimals);

// returns ['cat', 'dog', 'tiger', 'lion', 'giraffe', 'hippo']
 

The spread Operator has been around since JavaScript ES6. It helps in extracting properties from old objects or arrays to new ones.

Here’s a function which uses the Spread Operator :

function makeThingsEasy() {
     let line1 = ['how', 'are' , 'you' ,'doing'];
     let line2 = ['Hello!', ...line1, 'today'];
     return line2;
}

makeThingsEasy(); 

// outputs ['Hello!', 'how', 'are', 'you', 'doing', 'today']

Leave a Reply

Your email address will not be published. Required fields are marked *