Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript: Callback function code considered as string

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading