How does "+var === +var" work internally to verify if var is numeric?

JavascriptStringValidationNumbers

Javascript Problem Overview


Seeing this question: https://stackoverflow.com/questions/175739/is-there-a-built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number and this: jsperf, one of the presented approaches is this (mutatis mutandis):

var a = "123"
var b = "123b"

if ( +a === +a ) // true

if ( +b === +b ) // false

How does this logic work internally in JavaScript to make this possible?

My question is not how to check if a string is a valid number – this is already answered here: https://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric. I want to understand how the statement +a === +a works.

Javascript Solutions


Solution 1 - Javascript

+ converts the value to a number.

a gets converted to 123 and 123 === 123.

b gets converted to NaN but NaN !== NaN (because NaN is never equal to another NaN according step 4a of the equality rules).

Solution 2 - Javascript

The + operator here is known as the Unary Plus.

> The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

+"123" evaulates as 123.

+a === +a
-> +"123" === +"123"
  -> 123 === 123
    -> true

+"123b" evaluates as NaN (Not a Number), as the b character cannot be converted with the Unary Plus as without any prefix (like 0x for hexadecimal) the Unary Plus will assume the value is decimal (0-9). NaN is a special case in that it does not compare against anything, including itself:

NaN === NaN
-> false

NaN !== NaN
-> true

Because of this, our +b test case fails:

+b === +b
-> +"123b" === +"123b"
  -> NaN === NaN
    -> false

If you want both to evaluate to true we can add an isNaN() call at the end:

if ( +a === +a || isNaN(+a) )

if ( +b === +b || isNaN(+b) )

Solution 3 - Javascript

Solution 4 - Javascript

The two variables are string, but javascript convert automatically any string to a number when you + or - .

var a = "1";
var b = a;     // b = "1": a string
var c = +a;    // c = 1: a number
var d = -a;    // d = -1: a number

and Basically in your example you try to do this:

if ( +"123" === +"123" )  => ( 123 === 123) // true
if ( +"123b" === +"123b" ) => (NaN === NaN) // false

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaulo CoghiView Question on Stackoverflow
Solution 1 - JavascriptQuentinView Answer on Stackoverflow
Solution 2 - JavascriptJames DonnellyView Answer on Stackoverflow
Solution 3 - JavascriptDannyView Answer on Stackoverflow
Solution 4 - JavascriptAle_View Answer on Stackoverflow