Am a newbie in javascript, please help me understand below case where the callback function code is being considered as a string and passed as argument instead of passing the value of the callback function as an argument:
//Case3: Create Callback function in the argument section of calling statement.
function child3(callback,arg2=3) {
return console.log("Case3: callback function - parent function out:", callback arg2,"\n");
}
child3(parent3=()=>{
let a=1;
let b=1;
return a b;
},2);
Output:
Case3: callback function - parent function out: ()=>{
let a=1;
let b=1;
return a b;
}2
CodePudding user response:
When you use
, there are two possibilities:
- If both operands are numbers or BigInts, they are added together
- Otherwise, both operands are concatenated together into a string
If you do
callback arg2
and callback
isn't a number, the result will be a concatenation of it and arg2
. In your code, callback
is not a number; it's a function. You probably wanted to call the callback instead of concatenating it - eg, callback()
.
Another issue is that
child3(parent3=()=>{
should almost certainly be
child3(()=>{
unless you deliberately wanted to both create a new global function named parent3
and pass that to child3
.
function child3(callback, arg2 = 3) {
console.log(callback() arg2);
}
child3(() => {
let a = 1;
let b = 1;
return a b;
}, 2);
CodePudding user response:
It's not a string, but a parameter. It has a name in the function
's parameter list, which is callback
, so, inside the function
it is referred to as callback
and when you pass
"Case3: callback function - parent function out:", callback arg2,"\n"
to console.log
, you convert the function to string. By the way, you can do that without passing the function as parameter as well
function foo(a, b) {
return a b;
}
console.log(foo);
So, you do not pass it as a string, you pass it as a function instead, but it is converted into a string, i.e. the function definition when you call console.log
.