This code actually runs in this order:
- Calls
hello(3,3)
- Within% with% executes
hello
resulting in 4
- Calls
b+1
, values of hi(3, 4)
and a
- Within
b+1
multiplies and returns hi
and a
(result 12)
- Back to
b
return of hello
, which is 12, is returned
What you did not understand was that the addition is made before passing as an argument. Arguments are expressions that must be resolved before they are sent.
In theory the value of hi
would also be calculated before sending as an argument, however it is a simple expression that does not need to do calculations, so it is used as is.
It's interesting to understand this expression question to know what you can use where and what you'll be doing when you use an expression. By not understanding that a program location accepts expressions in general, beginner programmers often abuse variable creation. How many times do I see programs that make an expression, save it to a variable, and then use the variable in only one place in the program. This is done because the programmer has learned that a place accepts variables and it does not realize that instead of the variable it could put the direct expression. When you use the expression it is performed before it is used. We could understand your code this way:
function hi(a, b) {
return a * b;
}
function hello(a, b) {
temp = b + 1;
return hi(a, temp);
}
hello(3, 3);
Variables are storages, they are only needed when you need to store a value. And just need to save a value when you will use it more than once in the program. In some cases this can be useful when you need intermediate results.
Of course you can eventually create a variable that will be used only once for ease of readability. But this needs to be done consciously, not because you do not know that an expression might be being used.
Interestingly when the programmer learns that a place accepts expressions, it thinks that it can not use variables. Example:
if (x == 0 && y == 1)
could very well be written like this:
condicao = x == 0 && y == 1;
if (condicao)
Not everyone realizes this. I'm not saying that generally writing this way is interesting but it can be useful at some point.
As additional information the code is not returning a function, it returns the return of a function . This distinction is important because in fact a function can return another function, in which case it would be returning an algorithm rather than a result already computed. But it's not what you're doing.
This does something else and does not present the result you wanted:
function hello(a, b) {
return function(a, b) { return a * b };
}
hello(3, 3);