Do0msDay Do0msDay - 1 month ago 8
Javascript Question

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

counter = 1;
time = 60;

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


Why is the value of the code above 1 to 60

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

counter = 1;
time = 60;

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


I tested both of the codes with Node at the terminal.

Answer

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