Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript strict equality strangeness

If I do:

!isNaN('2') && parseInt('2').toString() === '2'    // returns 'true'

I have the following JavaScript function:

String.prototype.isDigit = function() {
    return !isNaN(this) && parseInt(this).toString() === this ? true : false;
}

However:

'2'.isDigit()    // returns 'false'

Furthermore,

String.prototype.isDigit = function() {
    return this === '2' ? true : false;
}
'2'.isDigit()    // returns 'false'

What is the discrepancy here? Shouldn't this === '2' ?

like image 324
JustAskin Avatar asked Dec 24 '22 17:12

JustAskin


2 Answers

Shouldn't this === '2' ?

No, actually. In this case, this is actually an instance of String, which is different from the string primitive '2'. this is essentially equal to new String('2'), and each instance of such an object is unique.

You could cast it to a string primitive though.

String.prototype.isDigit = function() {
    var that = '' + this;
    return !isNaN(that) && parseInt(that).toString() === that ? true : false;
}

'2'.isDigit();
like image 195
Alexander O'Mara Avatar answered Dec 28 '22 13:12

Alexander O'Mara


In your .isDigit() method, this is a String object (not a string primitive) and === with an object is only true if the two operands are exactly the same object, not just two separate objects with the same value or not with one an object and another a primitive.

So, in your method:

String.prototype.isDigit = function() {
    console.log(typeof parseInt(this).toString());   // "string"
    console.log(typeof this);                        // "object"
    return !isNaN(this) && parseInt(this).toString() === this ? true : false;
}

And, === will never be true for two operands that are different types.


You can stay with your approach, but use .valueOf() to get the primitive because comparing two string primitives with === just compares their values:

String.prototype.isDigit = function() {
    return !isNaN(this) && parseInt(this).toString() === this.valueOf();
}
like image 29
jfriend00 Avatar answered Dec 28 '22 13:12

jfriend00