0

On comparing string text to string object using ( == ) operator, returns true

var o = new String("ss");

var s = "ss";//return "ss" (string)

console.log(o);//return object    

console.log(o==s);//return true

How can i understand that?

  • The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick. – Dayan Mar 03 '17 at 15:59
  • What's a "Text" object? – Bergi Mar 03 '17 at 15:59

2 Answers2

2

That's because == is only comparing the value of o and s. === would compare the value and the type.

A little example:

console.log(1337 == "1337"); // true
console.log(1337 === "1337"); // false

console.log(1 == true); // true;
console.log(1 === true); // false

console.log("string" == new String("string")); // true
console.log("string" === new String("string")); // false

console.log(undefined == null); // true
console.log(undefined === null); // false
cyr_x
  • 13,987
  • 2
  • 32
  • 46
0

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:

exemple:

'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true

you can see the details in this link :link

Community
  • 1
  • 1
Mouaici_Med
  • 390
  • 2
  • 19