I’ve been having trouble understanding when to write functions as arguments with brackets and when not to do so and was hoping somebody could clarify it for me.
I feel like I have seen this in other frameworks or libraries but I am working through Redux and it’s what I’ll use as an example.
Sometimes when passing an already defined function to a Redux method, it can be passed just as a constant and others it needs to be followed by brackets. For example:
const store = Redux.createStore(reducerFunction);
That function does not require you to use brackets but:
store.dispatch( actionFunc() );
Does require you to follow it with brackets.
At first, I thought it had to do with ES6 arrow functions but I just passed the challenge below and It would not pass unless I added the brackets to an arrow function without parameters.
[https://learn.freecodecamp.org/front-end-libraries/redux/use-middleware-to-handle-asynchronous-actions/]
So my question is: is there any convention, general or specific for each framework, on how to write functions as arguments?
The first one is a reference to a function: the actual function, not the value it returns. So you are passing a function to a function.
In the second one, you are passing a value, not a function: actionFunc()
means execute actionFunc, and from that comes a value.
For example say you had this function that squares a number:
function square(n) {
return n * n;
}
And you had an array of numbers:
const nums = [2,3,4]
You can do this:
nums.map(square):
Because map
takes a function as an argument, then runs it for each element in the array. But you can’t do this:
nums.map( square() )
Because that doesn’t make sense, instead of a function, the value of square
if you execute it on its own is undefined
, so you would be saying “run undefined in each of the elements in this array”.
You could do
nums.map(n => square(n))
But that is [practically and mathematically] exactly the same as
nums.map(square)
Similarly, these are the same (there may be more arguments, this is just as an example, and always do it like the second example):
const store1 = Redux.createStore(r => reducerFunction(r));
const store2 = Redux.createStore(reducerFunction);
1 Like
duh!
Thank you!, I was over thinking it, I think I’ve read about it and completely forgotten it, wasn’t thinking about the return values or function calling.
Great explanation!
1 Like