Actually this code runs in this order:
- Flame
hello(3,3)
- Within
hello
executes b+1
resulting in 4
- Flame
hi(3, 4)
, the values of a
and b+1
- Within
hi
multiplies and returns a
and b
(result 12)
- Back to
hello
the return of hi
, which is 12, is returned
What you had not understood is that the addition is made before passing as argument. Arguments are expressions that must be solved before they are sent.
In theory the value of a
would also be calculated before sending as argument, however it is a simple expression that does not need to do calculations, so it is used as is.
It is interesting to understand this question of expressions to know what you can use where and what will be done when you use an expression. Because they do not understand that a local of the program accepts expressions in a general way the beginner programmers usually abuse variable creation. How often I see programs that make an expression, save it in a variable and then use the variable in only one place of the program. This is done because the programmer learned that a place accepts variables and he doesn’t realize that instead of the variable he could put 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 you only need to save a value when you will use it more than once in the program. In some cases this may be useful when you need intermediate results.
Of course, eventually you can create a variable that will only be used once to facilitate readability. But this needs to be done with awareness, not because you don’t know that an expression could be used.
Interestingly when the programmer learns that a place accepts expressions, he thinks he cannot use variables. Example:
if (x == 0 && y == 1)
could very well be written like this:
condicao = x == 0 && y == 1;
if (condicao)
Not everyone understands this. I’m not saying that writing in this way in general is interesting but can be useful at some specific 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 one function can return another function, in this case it would be returning an algorithm rather than an already calculated result. But it’s not what you’re doing.
This does other things and does not present the result you desired:
function hello(a, b) {
return function(a, b) { return a * b };
}
hello(3, 3);
I put in the Github for future reference.
I understand perfectly, thank you!
– RFL