Yasin Yaqoobi Yasin Yaqoobi - 1 month ago 19
Javascript Question

Javascript same method signature

Can someone please explain why we can simply pass a method name to a higher order function and everything works just fine. I know in something like Java I have to call the method

words
on each element individually. I was told that in Javascript if method signature matches we can simply pass in the name of the function with () and it will work. It is great but I want to know whats going on in the background. Why are we able to do this in javascript ?

function words(str) {
return str.split(" ");
}


var sentences = function(newArr){
return newArr.map(words);
}

Answer

In many languages you can pass a reference to a function as an argument to a function. That then allows the host function to use that argument and call that function when appropriate. That's all that is going on in Javascript. When you pass the name of a function without the () after it, you're just passing a reference to the function. That enables the host function to use that function as an argument and call it some time later.

In your specific example, .map() expects you to pass in a function that it will call once for each item in an array. So, you pass the name of a function that will then get called multiple times, once for each item in the array. That function you pass has a bit of a contract that it has to meet. It will be passed three arguments (value, index, array) and it must return a value that will be used to construct a new array.

In Javascript, since there is no argument type checking by the language, it is the developer's responsibility to make sure the arguments of the function you are passing match what the caller of that function will actually pass to it and you have to consult documentation of the calling code itself to know what arguments will be passed to it. You can name the arguments anything you want (that is entirely internal to your function implementation), but the order and the quantity of the arguments is determined by the caller and you must declare your function to match what the caller will provide.

Once thing that confused many in Javascript.

If you pass just a function name, you are passing a reference to the function (something that the host function can call at some later time).

array.map(myFn)        // passes a function reference

Or, use an inline function (same outcome):

array.map(function(value, index, arr) {
    // code goes here
})

If you put parens at the end of the function name, then the function is executed immediately and the return value of that function execution is what is passed:

array.push(myFn());    // pushes the result of calling myFn()
Comments