Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a JavaScript String not a string? [duplicate]

Tags:

javascript

Possible Duplicate:
Why does (“foo” === new String(“foo”)) evaluate to false in JavaScript?

Over here I caught the advice that it's best to use non type-coercive string comparison, but in Chrome, I discovered something kind of odd:

var t1 = String("Hello world!");
var t2 = new String("Hello world!");
var b1 = (t1==t2); // true
var b2 = (t1===t2); // false

Is this standard behavior? If so, what are the respective types of t1 and t2? Thanks.

like image 305
Nathan Andrew Mullenax Avatar asked Aug 15 '12 21:08

Nathan Andrew Mullenax


1 Answers

If you don't use the "new" keyword with String, you get a primitive string.

If you use "new" keyword, you get a string object instead of primitive.

When you use == it will try to convert to a comparable type, so it can be equal.

If you use ===, it won't convert, so an object can not equal a primitive.

like image 147
gray state is coming Avatar answered Sep 21 '22 04:09

gray state is coming