Lets explain the Code:
Step 1: const str = "hello";
What Happens:
-
A primitive string is declared and stored in the constant variable
str
. - The value of
str
is "hello".
Important:
- In JavaScript, primitive strings (like
"hello"
) are not objects. - They are immutable primitive data types.
Step 2: str.data = "val";
What Are We Trying to Do?
You are attempting to add a custom property called data
to the string primitive.
Does This Work?
No, it won’t work.
Here’s why:
Detailed Explanation:
When you try to access or set a property on a primitive (like a string, number, or boolean), JavaScript temporarily wraps the primitive inside an object wrapper.
Example:
When you write:
JavaScript behind the scenes does this:
This wrapper object is temporary.
What Happens Next:
- The temporary object is created.
- The
data
property is assigned to that temporary object. - Immediately after this line, the wrapper object is destroyed.
- The primitive
str
itself never holds this property.
So, when you do:
It tries to access the data
property on the primitive string again.
- JavaScript again wraps the string in a new, fresh object.
- This new wrapper does not have the
data
property.
Final Result:
The console will log:
Why This Happens: Detailed Rules
Primitive values (string, number, boolean, symbol, bigint) cannot hold custom properties.
When you try to assign a property:
JavaScript wraps the primitive into a temporary object.
-
The assignment affects this temporary object, not the primitive itself.
-
Once the operation completes, the wrapper object is discarded.
-
On property access, JavaScript again wraps the primitive into a new temporary object that has no memory of the previous assignment.
Visual Flow:
Key Takeaways:
- Primitive types are immutable and cannot hold custom properties.
- JavaScript temporarily wraps primitives when you try to access or set properties.
- The temporary wrapper is destroyed immediately after the operation.
- To store custom properties, you must use objects, not primitives.
How to Make This Work (Proper Way):
If you want to store properties, you should use an object:
This works because now str
is an object, not a primitive.
✔ Final Answer:
B) undefined
This question appeared in the IBM 2nd round of interview, testing the candidate’s knowledge of prototype and string custom property in JavaScript.