Search code examples
javascriptnode.jsread-eval-print-loop

Difference between ++ and += 1 at the REPL with Node


counter  = 1;
time = 60;

while (counter < time) {
    console.log(counter);
    counter += 1;
}

Why is the value of the code in REPL above 1 to 60

While the output of the code in REPL below is 1 to 59:

counter  = 1;
time = 60;

while (counter < time) {
    console.log(counter);
    counter++;
}

I tested both of the codes in the REPL.


Solution

  • It is because node REPL by default print out the result of the last command.

    In your first case, the last command is counter++, which increase counter to 60 and returns 59

    In the second case, the last command is count += 1, which increase counter to 60 and returns 60

    It is more clear if you run it inside Chrome developer console

    enter image description here

    In the node REPL case, you can still see the difference that the last number have different color, indicated it is the value of last evaluation instead of output of console.log

    enter image description here