Our Javascript Code :-
1. Creating the object
- You declare a variable
obj
and assign it an object with one property: - key:
"age"
- value:
24
2. Destructuring with a new name
- This is object destructuring plus aliasing.
The pattern on the left
Look up the property{ age: userage }
means:age
onobj
.- Take its value (
24
) and assign it to a brand‑new variable nameduserage
. - Important: This does not create a variable called
age
—onlyuserage
.
3. console.log(age);
- You try to log
age
, but: - You never declared a standalone variable named
age
. - The destructuring created only
userage
. Result: a ReferenceError
4. console.log(userage);
userage
was declared by the destructuring.- Its value is
24
. - Result: 24
5. How to fix it if you do want a variable named age
If you want both a local variable called age
and one called userage
, you could do:
- Here
{ age, age: userage }
first createsage = obj.age
, then also aliases it touserage
.
Or, if you only need age
:
Key Points :-
- Destructuring can rename properties:
{ propName: localVar }
. - Only the names you list on the left get declared.
- Trying to reference a variable you never declared always throws a ReferenceError.
✔ Final Answer:
B) ReferenceError
This question appeared in the Infosys 1st round of interview, testing the candidate’s knowledge of Object Destructuring in JavaScript.