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++);
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++);
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++
Let lhs be the result of evaluating LeftHandSideExpression.
Let oldValue be ? ToNumber(? GetValue(lhs)).
Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 12.8.5).
Perform ? PutValue(lhs, newValue).
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!
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.
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.