-6

When the following line of code is executed in node.js console the result is:

var string = 'abc'; string++;
// NaN
string;
// NaN

I thought that it should work like this:

var string = 'abc'; string++;
// 'abc';
string;
// NaN

My rationale:

Because ++ is a post-increment operator, meaning it returns the old value (in this case abc) and then it adds 1 to the string, gets abc1, which is Not A Number, but the ++ operator should return a nubmer, so it returns specialNaN number and assigns it to variable string

Please specify where I am wrong.

Chad
  • 693
  • 5
  • 17
Alexander
  • 257
  • 1
  • 3
  • 11

2 Answers2

3

++ if used on a string , first tries to convert it to a number if the conversion fails you get NaN.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
3

The way that the ++ "postfix" increment operator works involves first performing a conversion to number type. The value of that conversion is always the return value from the operation, even if that value is NaN.

Pointy
  • 405,095
  • 59
  • 585
  • 614