I had started to learn JavaScript for web development and I am currently stuck at a point in the callback function. The problem is that I can’t understand how arguments are passed in JavaScript.
CODE:
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
function myfunc(value){ //i had set a parameter 'value'
console.log(value); // i had printed the 'value'
}
arr.forEach(myfunc); // i had not passed any argument in myfunc
I am really confused about how myfunc (value) gets the ‘value’ parameter from in forEach function or any functions like:
const numbers1 = [45, 4, 9, 16, 25];
function myFunction(value) { //myFunction has parameter 'value'
return value * 2;
}
const numbers2 = numbers1.map(myFunction); /* here, how value arguments are passed to
myFunction? */
>Solution :
The functional extensions on the javascript Array require a function as an argument. That function can be:
- A named function
function doSomething() {} // This is a named function
- An anonymous function
// This is an anonymous function because we didnt give a name to it
[1,2,3].forEach(function (value) { console.log(value) })
- A fat-arrow function (lambda expression).
// It's called fat arrow because well, the arrow is fat
[1,2,3].forEach((value) => console.log('hey', value))
The implementation for the functional extensions on Array always pass three arguments: the value, the index and the array the function is being applied to
The way function arguments work in JS is that if you pass more than the required arguments to a function JS will just drop the rest, and if you pass more than the ones needed those will have a value of undefined unless you have specified a default value for those
const array = [1,2,3]
// I am just getting the value and the name "value" could be any name
array.forEach((value) => console.log(value))
// here my fat-arrow function takes two parameters, since forEach passes three parameters we're good to go
array.forEach((value, index) => console.log(value, 'at', index))
// Here we're using all arguments without dropping any
array.forEach((value, index, array) => console.log(value, index, array))
// that is because the forEach predicate only passes three arguments and hence the last is undefined
array.forEach((value, index, array, fourth) => console.log('here', fourth, 'is always undefined'))