Let’s dive deep into our code and understand how primitive strings and String objects behave differently in JavaScript. Here's the code :-
Step-by-Step Explanation :-
Step 1: Variable Declarations
s1
is a primitive string. It’s stored as a simple, immutable value.- Internally, JavaScript stores
'hello'
as a sequence of characters.
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:
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
vsobject
)- Are they the same value? → Doesn’t matter — the types don’t match
- So, it returns
false
.
false
Summary Output
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.