5

The 1st console.log output is 2. No doubt.
But why the 2nd console.log output is not undefined? Shouldn't output the undefined at first, then the variable b becomes NaN?

var a = 2;
console.log(a++);

var b;
console.log(b++);
Danson Lin
  • 51
  • 3

3 Answers3

8

Consider this:

b = "foo"
c = b++
console.log(c) 

Since the postfix ++ returns the value before incrementing, we expect c to be foo, however, it's NaN. Why is that?

This is by design, and described as follows in the standard (emphasis mine):

12.4.4.1 Runtime Semantics: Evaluation

UpdateExpression:LeftHandSideExpression++

  1. Let lhs be the result of evaluating LeftHandSideExpression.

  2. Let oldValue be ? ToNumber(? GetValue(lhs)).

  3. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 12.8.5).

  4. Perform ? PutValue(lhs, newValue).

  5. Return oldValue.

Translated to quasi-JavaScript, the above algorithm would be:

 function postIncrement(someVariable) {
     let oldValue = Number(someVariable.value); // Note "Number" here
     let newValue = oldValue + 1;
     someVariable.value = newValue;
     return oldValue;
 }

In other words, value++ returns not just the value, but the value converted to a number. The conversion takes place before incrementing, and, since Number("foo") is NaN, this is what we get.

Yet another JavaScript quirk to take note of!

georg
  • 211,518
  • 52
  • 313
  • 390
-3

You need to assign value to b or check for null condition before logging b. b is NaN because its b++ is check for number.

-3

var a = 2;

Here you have declared a variable "a" with a value of "2", making its datatype "INTEGER".

console.log(a++);

The output is 2 and the variable "a" has a value of "3".

var b;

Here you have declared a variable "b" without any value, making its datatype "UNDEFINED".

console.log(b++);

The output is NaN because the variable "b" is null, and therefore increment operator cannot be applied.

  • 1
    `The output is NaN because the variable "b" doesnot have a default value` this sentence isn't correct. Please refer to @georg comment for more details. – slesh Oct 01 '19 at 08:03
  • @slesh this line is 100% correct, The output is NaN because the variable "b" doesnot have a default value, as b without any initial value has a value null, you cannot apply ++ to null value, hence it is Nan – Muhammad Hamza Mirza Oct 01 '19 at 08:10
  • 1
    You got *NaN* because you apply the arithmetic operation to *undefined*, but not because *b* doesn't have a default value. – slesh Oct 01 '19 at 08:20