spread syntax

JavaScript has Spread Syntax which allows you to expand arrays or other iterable objects. It is very useful when you are trying to pass elements of an array as separate arguments to a function.

Syntax

for array literals

JavaScript

let arrOfNumbers = [0, 2, 3, 4];

let newArray = ["five", ...arrOfNumbers, 10]

console.log(newArray);
 // ["five", 0, 2, 3, 4, 10]

for function calls

JavaScript

let Arr = [3, "five"];

myFunction(...Arr)

Examples

When using the Spread Syntax you will no longer need to use apply when you have an array of values that you want as arguments for a function call.

with apply

JavaScript

let arrOfNumbers = [0, 2, 3, 4];

const biggestNumber = Math.max.apply(null, arrOfNumbers);
console.log(biggestNumber);

with Spread Syntax

JavaScript

let arrOfNumbers = [0, 2, 3, 4];

const biggestNumber = Math.max(...arrOfNumbers);

console.log(biggestNumber);
 // 4

JavaScript Spread Syntax goes only 1 level when making a copy which means that when objects in a clone array are changed it will alter the objects in the original arr.

JavaScript

let arr1 = [{ "name": "brian" }];
let arr2 = [...arr1];

arr2[0].name = "Joe";

console.log(arr1[0])
 // {name: "Joe"}
console.log(arr2[0])
 // {name: "Joe"}

JavaScript Spread Syntax allows you to concat arrays.

without Spread Syntax

JavaScript

let arr1 = [0, [1, 2],"apple"];
let arr2 = ["three", 4, "string"];

arr1 = arr1.concat(arr2);

console.log(arr1);
// [0, [1, 2], "apple", "three", 4, "string"]

with spread syntax

JavaScript

let arr1 = [0, [1, 2],"apple"];
let arr2 = ["three", 4, "string"];

arr1 = [...arr1, ...arr2];

console.log(arr1);
// [0, [1, 2], "apple", "three", 4, "string"]

Conclusion

The Spread Syntax is very useful when you are trying to pass the elements of an array as single arguments to a function. It ultimately replaces apply and replaces multiple function on the Array.prototype.

html
css
javascript
What is Git and Github

Git is the tool that we can use to save all changes and additions to our code on the computer we're working on. GitHub is the online location we can upload our Git-managed code to for safekeeping.

html
Divs and spans in HTML

Classes are great for selectively applying styles to certain parts of your web pages. But sometimes you'll have entire sections of your pages that you want to style a certain way, and adding a style to every tag gets annoying. Divs and spans can help.