GoConqr hat ein neues Design! Sag uns, wie es dir gefällt.

Modul 5 von 10 · Medien

Spread Mdn

Kostas Diakogiannis

Spread Mdn

The Spread operator

Spread operator splits all the contents of a collection (could be either array or object) into a series of individual elements. Thus they can be put inside functions as arguments or as elements to pollute other arrays.

For example: 

const testScores = [20, 25, 35];

Imagine you have a function that accepts three arguments and returns the biggest number of them.

For example:

function findBiggest(firstNumber, secondNumber, thirdNumber) { }

If you put the testScores there as a argument when calling the function you get an error, because the function expects three arguments, and testScores is a single variable (an Array!).

What you can do is to SPREAD these values the testScores array contains and assign them separately to each argument. You can do it by spreading these values out of the array.

How: By using the three dots syntax that spreads them out. So when calling the function instead of doing it by index like :

findBiggest(testScores[0], testScores[1], testScores[2]). This is going to work but is inneficient. #dont_do_that

Alternatively you can do:

findBiggest(...testScores) .This will individually take EACH value of the testScores and assign it to each function's argument. 

It is equivalent to typing:

findBiggest(20, 25, 35);

This is very useful when you want to find the max or min of an array because JavaScript provides already function that accept a sequence of numbers and not an array. If you already have everything inside an array you can spread all the values as you saw.

Note: It is a new ES6 feature. Check documentation here!

Anleitung

Um im Kurs weiterzukommen, sende einen Versuch dieses Quiz ab. Du kannst ihn nach der letzten Frage absenden.

Zum gewählten Modul

Feedback

Worum geht es?

Wie gefällt dir das neue Design?

Dein Eindruck