JavaScript help about increment

JavaScript help about increment
0

I’ve a query:

var num = 0;
var newNum = num++;
console.log(newNum);

This code prints 0 in console. While the code below prints 1 in console,

var num = 0;
num++;
console.log(num);

The first code should also print 1 but it doesn’t. Why?
And in for loop we add ++ after i. Why can’t we add ++ before i?
eg.

for (var i = 0; i < string.length; i++)

Hi, I think there is a misunderstanding about how increment is supposed to work. From the mdn docs:

The increment operator increments (adds one to) its operand and returns a value.

  • If used postfix, with operator after operand (for example, x++), then it increments and returns the value before incrementing.
  • If used prefix, with operator before operand (for example, ++x), then it increments and returns the value after incrementing.
2 Likes

You can google difference between post increment and pre increment

num++ or post increment will return the old num value so newNum has the value of 0 and then add 1 to num.

++num or pre increment will add 1 to num and return the value of num which is 1.

and
for (var i = 0; i < string.length; ++i)
you could definitely write that.

1 Like

Thanks you cleared my doubts