DEV Community

Discussion on: Function

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

This is not how function invocations work:

// First javaScript read the declaration function with name timesTwo
function timesTwo (num) {
  return num * 2
}
/*  Second read the declaration variable with name result and see that 
 the value hold is a function timesTwo */
const result = timesTwo(8)
/* Third javascript came back and replace the parameter num with the value 8  */
function timesTwo (8) {
  return 8 * 2
}
function timesTwo (8) {
  return 8 * 2 /* <= Fourth javascript run the block of code that result
   16 */
}
/*  Finally replace the expression (function) in the right side
 of the variable with our result 16 that became the value of 
our const result */
const result = 16
console.log(result) // then we log the result == 16

You might want to look into stack frames to understand what's really going on. This part is especially misleading to beginners:

/*  Second read the declaration variable with name result and see that 
 the value hold is a function timesTwo */
const result = timesTwo(8)
/* Third javascript came back and replace the parameter num with the value 8  */
function timesTwo (8) {
  return 8 * 2
}
Collapse
 
giandodev profile image
GiandoDev

Thank you so much for your feedback 🙏

Collapse
 
giandodev profile image
GiandoDev • Edited

I am sorry I will try to write it better in the mean times for you this is better :
function myFunction(a, b) {
return a * b;
}
myFunction(10, 2); // Function invocation, will return 20

//optional parameters (es6 only)
//allow to set optional parameters

function myFunction(a, b = 10) {
return a * b;
}
myFunction(1); // Function invocation, will return 10
myFunction(1,5); // Function invocation, will return 5