How do parameters work in ES6 arrow functions? - Kevin Chisholm Video

Опубликовано: 31 Январь 2018
на канале: Kevin Chisholm
140
2

https://blog.kevinchisholm.com/javasc...


In this video, I’ll show you how parameters work in ES6 arrow functions.

With ES6 arrow functions, the syntax for parameters will vary, depending on the number of parameters you have. So in this example, I have two arrays. The first one’s called days, and it’s simply the words Monday, Tuesday, and Wednesday, and the second one is months and that has the words January, February, and march.

So in each case I’m simply looping over the array. So in example number one I’m saying days for each, and I’m outputting the value of days. So I wind up with Monday, Tuesday, and Wednesday in the DOM. And in the second example I’m outputting, I’m saying months for each and I’m outputting the value of each month. And I wind up with January, February, march. There is a 0 1 2 there; we’ll explain in a minute.

So in the first case I only have one parameter and when that’s the case I just simply use the parameters. So I just say day and then the arrow sign and the body of the function right here. In the second case, I have two parameters, because I know that the second argument, that the callback to the for each method perceives is the index of the elements of the first index’s 0, the second index’s 1, and the third index’s 2, and so forth.

And if I want to use that, I need to get that parameter. So, in this case, I need to wrap that with parentheses, because when I have two or more parameters with arrow functions, I need to wrap it with parentheses. One parameter, nothing needed. With two parameters, I need to wrap it with parentheses.

So what if I wanted to ignore the value of the array element. For example, if I get rid of this, and let’s say I just want to output the word “hello,” as I loop through the days array. Now that’s not very interesting and it’s certainly not very useful or dynamic, because we’re not using the actual array element.

But lets’ say I don’t care. I don’t care about day, and I take it away. Now I take it away I’m going to get and error, so I have to do something there. And what I do is use open and closing parentheses. So when you have no parameters in an arrow function, you need to use open and closing parentheses. When you have one parameter, you just simply use the parameter, and when you have two or more parameters you need to wrap those parameters in open and closing parentheses.

If you found this video helpful, you can subscribe to my channel by clicking the red "Subscribe" button right under the video. You can also take a look at my blog, where there are many articles and tutorials about web development.

Thanks very much for watching.