JavaScript spread operator

JavaScript spread operator is a useful operator for manipulation of objects , strings and arrays in JavaScript among others you can you it to effectively copy an object or array expand it or even convert a string into an array of its constituent characters.

const chars = ["a", "b", "c"]
const name = "John swana"

Copying an array using spread operator
to copy an array using a spread operator you can do it using the syntax as follows

var alphabet = [...chars]
And now alphabet contains chars properties
alphabet // ["a", "b", "c"]

Copying an object using spread operator
Similarly you can copy JavaScript objects using spread operator. Take for instance
const object = {name:  "John swana", gender: "male"}
var user = {...object}
user //  {name:  "John swana", gender: "male"}

Converting a string into an array
Note that you can use String.prototype.split for this operation if you want
var array = [...name]
// ['J', 'o', 'h', 'n', ' ', 's', 'w', 'a', 'n', 'a']

Wrapup I've explained on JavaScript spread operator

Comments

Popular posts from this blog

What is 'this.' keyword in JavaScript

How to iterate array elements using 'for loop' in JavaScript