+ 1
Executing a function assigned to a variable in JS
Hello. If I create a function called Multiply, that multiplies "a" by "b" : function Multiply(a, b) {return a * b; } And then I assign this function to the variable "x" and I input the values 5 and 6 for "a" and "b" : var x = Multiply(5, 6); And then I use document.write to display the value of "x": document.write(x); The result will be 30. Pretty simple, right? Well, my question is, when exactly is "return a*b" executed? Is it when I assign this function to "x"? Or is it calculated when I use document.write(x)?
3 Respuestas
+ 2
After you called the function Multiply(5,6); that will be calclated🙃
+ 3
"When exactly is 'retun a*b' executed"
~OP
As retun a*b; is a statement within function `Multiply` it'll be executed when function is called.
You need to put parantheses () after function name in order to call it. If it accepts any arguments they will go within ().
let x = function multiply(a,b){
return a*bm
}
document.write( x(2,5) );
When you print `x` it'll not execute function. Its default toString method will be invoked.
document.write(x)
output: function multiply(a,b){ return a*b }
+ 2
You are not assigning the function itself, but the result of a function call.
So first the function is executed, then the return value 30 is stored in x.