Reputation: 1
can someone explain please how it works? when calling the function it logs the "some value"
function a(pass){
pass("some value");
}
a(q=>{
console.log(q);
});
however if i call the function like this,i get an error "pass is not a function"
function a(pass){
pass("some value");
}
console.log(a());
and like this,error "argument" is not defined.
function a(pass){
pass("some value");
}
console.log(a(argument));
Upvotes: 0
Views: 49
Reputation: 363
You need a pass function because you're calling it when you call function a().
function a(pass){
pass("some value");
}
console.log(a());
function pass(xyz){
alert('hey');
}
Upvotes: 0
Reputation: 36564
The function a
in the above code is an higher order function. Because it expects another function as argument.
In the first example the first variable is a function so value
will a function. So due to
pass("some value");
it will be called.
In the second example you donot pass anything to the function a
so pass
will be undefined
. And when you use function calling syntax for any variable which is not a function it will throw error.
In the third example you are trying pass the variable argument
to function a
. But argument
doesn't exist so it throws error.
Upvotes: 0
Reputation: 1032
Welcome.
1: Here you have passed a function as an argument. The function performs a console.log of the value provided in function a.
2: Here you have provided no function. You are calling a()
. There is no definition for a()
. There is only a definition for a(pass)
. You must call it with a parameter. If you do not, it is as if you called a(undefined)
. Now a tries to do undefined('some value')
, throwing error.
3: Here, what is argument? remove the function a() { }
code and see you are trying to perform a(argument)
but argument
is not defined anywhere, and JS cannot determine what is argument.
Upvotes: 0
Reputation: 2671
Example 1:
function a(pass){
pass("some value");
}
a(q=>{
console.log(q);
});
In this instance you are passing q=>{console.log(q);}
through to the function a. So it calls that and outputs something in the console.
Example 2:
function a(pass){
pass("some value");
}
console.log(a());
In this case, you are passing no parameter through to function a. So the function attempts to call an undefined parameter which by definition is not a function.
Example 3:
function a(pass){
pass("some value");
}
console.log(a(argument));
In this case you are passing an undefined variable called argument
to function a which results in the error message that you get. I hope this helps.
Upvotes: 1