简体   繁体   中英

Javascript weird comparison result

I have two strings declared in Javascript as follows:

var str1 = new String('Hello');
var str2 = 'Hello';

Comparison results:

str1 == str2 // true
str1 === str2 // false

My questions is, why is === yields to false when both strings are equal in value and have the same string type?

You're comparing a String object with a primitive string. Those are two different types.

To make it clearer, here are all JS types :

  • Six data types that are primitives:
    • Boolean
    • Null
    • Undefined
    • Number
    • String
    • Symbol (new in ECMAScript 6)
  • and Object

When compared using === , an object is only equal to itself (and thus not to a primitive value nor to another identical object)

When comparing using == , EcmaScript follows this procedure , which calls the toString method on the String object.

There's normally no reason to explicitly use String objects (you implicitly use them every time your code needs an object and you pass a string, but the JS engine handles the promotion for you). You should almost always stick to primitive strings.

Because

typeof new String('Hello') === 'object'

and

typeof 'Hello' === 'string'

The former is an object, the latter is a primitive.

The == check works because the String object has also toString method and JS invokes that method in this case (as well as when concatenating with other string).

A string object is not a primitive string and therefore will not be equal completely by using === . Instead, if you insist on using === you can use the valueOf function, like:

new String("hello").valueOf() === str2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM