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

How to make a html5 breakout game in JavaScript

How to tabulate array key values using console.table

How to set content disposition headers for express nodejs apps

Ways of iterating Object properties in JavaScript

How to evaluate a string on a regular expression rule in JavaScript