1

Why does comparing an explicitly called String constructor to an implicit string evaluate true, but adding the new keyword makes it evaluate false on deep equals, but true again on shallow equals?

> "hello"===String("hello")
true
> "hello"==new String("hello")
true
> "hello"===new String("hello")
false

Edit: after further testing, this appears to happen with all types that have implicit constructors.

Edit 2: to clarify, this is not a question of == vs. ===, but one of implicit vs. explicit constructors.

Valkyrie
  • 841
  • 1
  • 9
  • 22
  • 4
    `typeof "hello"` → `'string'`, `typeof new String("hello")` → `'object'` – Biffen Jan 30 '17 at 17:16
  • 1
    `==` checks just for the value (`"4" == 4 > true`) but `===` checks for the type as well. (`"4" === 4 > false`) since one is a string and the other is a number. – ibrahim mahrir Jan 30 '17 at 17:18
  • @ibrahimmahrir: They both check the type. The `==` enters a type coercion algorithm if it finds that the types are not the same. If `==`only checked the value, then `4 == "4"` would be `false`. –  Jan 30 '17 at 17:36
  • 1
    Possible duplicate of [Which equals operator (== vs ===) should be used in JavaScript comparisons?](http://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) – brandonscript Jan 30 '17 at 17:37

2 Answers2

5

When you use the new keyword you are creating an object. If you were to check the typeof new String('hello') you will see that it is of type object. Checking the type of 'hello' on its own will yield string.

As you may know, using a strict equals operator (===) will check for both value and type, so it will return false due to the types not matching.

The reason the expression without the new keyword returns true is because calling upon the String global object is not the same as calling the constructor using new:

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.

As such, the type of the return value will be string and not object, so the strict check will return true.

Pabs123
  • 3,385
  • 13
  • 29
1

The difference between == and === is that === requires the type to be the same, while == does not.

So this is telling you that both "hello" and String("hello") are of the same type (which is string); but new String("hello"), while it has the same value, is a different type (which is object)

Mark Adelsberger
  • 42,148
  • 4
  • 35
  • 52