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
>Solution :
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);