undefinedfix
Sign in

A simple JS function, the results of interpretation

dlk5730 edited in Mon, 12 Sep 2022
function a(){
    var num = 0;
    for(var i = 0;i < 10;i++){
        num = num++;
    } 
    console.log(num);
};
a();

Why is the result 0?

6 Replies
Raj
commented on Mon, 12 Sep 2022

num ++ It will autoincrement num and return the original value of num.

Num = num + +; the original value of num (the value before autoincrement, 0) is assigned to num, so num = num + + does not change the value of num as a whole.


As for the order of value added in the comments, let's go to the standard. Self increase:

Let lhs be the result of evaluating LeftHandSideExpression.Let oldValue be ? ToNumber(? GetValue(lhs)).Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 12.8.5).Perform ? PutValue(lhs, newValue).Return oldValue.

You can see num + +, which completes the auto increment (step 4) before returning. Assignment can only be performed after getting the return. Naturally, the old value is assigned to num (which has been self incremented).

Note that this sentence may have different interpretations in different programming languages

czuqs
commented on Mon, 12 Sep 2022

++After that, assign value first and then add value; before + +, assign value first and then add value

function a(){
    var num = 0;
    for(var i = 0;i < 10;i++){
        num = ++num;
    } 
    console.log(num);
};
a();
lnjlb
commented on Mon, 12 Sep 2022

num=num++

  1. Num + + is 0, then num value increases to 1
  2. The left side of the equal sign is assigned the result of num + +, that is, the final num = 0
ScarlettRogue
commented on Tue, 13 Sep 2022

num ++ It's used first and then added, so num = num ++ It's equal to num = 0; You can set num = num ++ Change to num ++ That's it.

Link64
commented on Tue, 13 Sep 2022

It's better to avoid using num + +, and it's not easy to make mistakes when using + + num

aleonjhon
commented on Tue, 13 Sep 2022

There's no need to study this, because it's meaningless. Don't use it. Just write it on a single line. I dare ask you, how many are not wise after the event, do you know before the event!

JS has more details like this, can you remember?