I am having a statement like
var x = parseInt(1)+'b';
why this result is 1b but isNAN('b')
is returning true;
so result should be NaN?
I am having a statement like
var x = parseInt(1)+'b';
why this result is 1b but isNAN('b')
is returning true;
so result should be NaN?
- 1 You got the answers already but also check the Documentation on Expressions and operators - String Operators – Nope Commented Jan 10, 2017 at 17:19
- Short answer: because it isn't an arithmetic operation :) – Álvaro González Commented Jan 10, 2017 at 17:29
4 Answers
Reset to default 12Number + String
is not an arithmetic operation.
In the Number + String
statement, engine will convert the number into string equivalent.
In your case it will be 1 -> '1'
. And then will be simple strings concatenation, because +
operator will concatenate two strings.
'1' + 'b' === '1b';
Code Snippet
console.log(1 + 'b');
In case with IsNaN('b')
, it tries to detect is the parameter a number or not. 'b'
is not a number (NaN
), so it will return true
.
Code Snippet
console.log(isNaN('b'));
For more see Documentation
Because it's not an arithmetic operation, it's a string concatenation. Whenever either operand to +
is a string, string concatenation is done rather than addition; details in the spec. If the other operand isn't a string, it's convered to string. So you end up with "1" + "b"
=> "1b"
.
The +
operator is defined as concatenation if either operand is a string.
Source: https://www.ecma-international/ecma-262/5.1/#sec-11.6.1
The +
operator, when it has a string as one of it's arguments, will be interpreted as a "concatenation" operator instead of "addition". The non-string value will be converted to a string and appended to or prepended to the string value, depending on whether or not it is to the right or the left (respectively) of the operator.