Avoid This JavaScript Mistake: Misunderstanding Destructuring with Renaming, Object Destructuring in JS, Asked in Infosys

Avoid This JavaScript Mistake Misunderstanding Destructuring with Renaming Object Destructuring in JS Asked in Infosys

Our Javascript Code :-

let obj = { age: 24 };
let { age: userage } = obj; console.log(age); console.log(userage);

1. Creating the object

let obj = { age: 24 };
  • You declare a variable obj and assign it an object with one property:
    • key: "age"
    • value: 24


2. Destructuring with a new name

let { age: userage } = obj;
  • This is object destructuring plus aliasing.
    • The pattern on the left { age: userage } means:

      Look up the property age on obj.
    • Take its value (24) and assign it to a brand‑new variable named userage.
  • Important: This does not create a variable called age—only userage.

3. console.log(age);

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

ReferenceError: age is not defined

4. console.log(userage);

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:

let { age, age: userage } = obj;
console.log(age); // 24 console.log(userage); // 24

  • Here { age, age: userage } first creates age = obj.age, then also aliases it to userage.

Or, if you only need age:

let { age } = obj;
console.log(age); // 24

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.

Post a Comment

Previous Post Next Post