CodeOrc.com - Learn by example
X
Make an RPG
Vue Implementations

Examples of how to use Spread Attributes

FYI, In these examples, we're just going to use our log function to output stuff to DOM and the console.

Elements to Array

Spread attributes can turn your parameters/arguments into an array. For example:

function eat(...foods) { log(foods); }
eat("carrot", "beans", "rice");
DO IT

Without the ... operator, foods would be "carrot". But, with the ... operator, when you run the above code, the console will print out an array.

Open the Developer console (Ctrl-Shift-I and see for yourself). Try removing the ... and putting it back in, running it both ways.

Array to Elements

Spread attributes can also do the reverse, by simply using the spread operator ... when you call the function with an array. For example:

function eat(foods, foods2) { log(foods); log(foods2); } var fruits = ["berry", "melon"]; eat( ...fruits );
DO IT
Can you add more fruits? Don't forget to add more parameters in the eat function.

As you can see, when you call the eat function with the fruits array, it goes in as an array. But, inside the function, each of the elements has been expanded to it's own parameter. Go ahead and play with it until you understand how it works.

In the next lesson, we will learn about Examples of Let and Const

Get the Latest Tutorial Updates
<< >>
X