Why 'hello' == new String('hello') is True, but === is False – JavaScript Explained, Primitive vs Object: The Truth Behind JavaScript String Comparison Confusion: == vs === with new String().

Why hello double equal new Stringhello is True but tripal equal is False JavaScript Explained Primitive vs Object The Truth Behind JavaScript String Comparison Confusion double equal vs tripal equal with new String

Let’s dive deep into our code and understand how primitive strings and String objects behave differently in JavaScript. Here's the code :-

const s1 = 'hello';
const s2 = new String('hello'); console.log(s1 == s2); console.log(s1 === s2);

Step-by-Step Explanation :-

Step 1: Variable Declarations

const s1 = 'hello';

  • s1 is a primitive string. It’s stored as a simple, immutable value.
  • Internally, JavaScript stores 'hello' as a sequence of characters.

const s2 = new String('hello');
  • s2 is a String object.
  • When you use new String(...), you are explicitly creating an object wrapper around a string.
  • So s2 is not a primitive — it’s of type object.

To confirm:

typeof s1; // "string"
typeof s2; // "object"

Step 2: Comparisons

🔸 1. console.log(s1 == s2);

  • This uses loose equality (==), which allows type coercion.
  • JavaScript sees a comparison between a primitive and an object.
  • So it tries to convert the object to a primitive for comparison:

    • s2.valueOf() returns the primitive 'hello'
  • Now it's 'hello' == 'hello' →  true

✔️ Output: true


🔸 2. console.log(s1 === s2);

  • This uses strict equality (===), which does not allow type coercion.
    • It checks: 

      Are they the same type? → No (string vs object)
    • Are they the same value? → Doesn’t matter — the types don’t match
  • So, it returns false.
✖️ Output: false


Summary Output

true // s1 == s2 (type coercion happens)
false // s1 === s2 (different types: primitive vs object)

✔ Final Answer:

D) true false

This question appeared in the Mindtree 2nd round of interview, testing the candidate’s knowledge of comparisons operator between string and wrapper object of string created using new keyword in JavaScript.

Post a Comment

Previous Post Next Post