Andrey Bushman
Andrey Bushman

Reputation: 12476

JavaScript: Why I get `undefined` when I use an assignment with destructuring?

JavaScript, Google Chrome

This is my code example. Why I get the undefined values?

let foo = {name: 'Bob', age: 24};
let {name, age} = foo;

console.log(name); // 'Bob'
console.log(age); // 24

foo = {color: 'red', result: true};
({name, age} = foo);

console.log(name); // "undefined" instead of 'red'
console.log(age); // undefined instead of true

Upvotes: 0

Views: 74

Answers (3)

user234932
user234932

Reputation:

Destructuring the way you did it will match on the keys, not position (you can't really depend on the key order in objects).

const {foo} = {foo: "bar"}

is the equivalent of saying

const foo = ({foo: "bar"}).foo

Upvotes: 4

wintermute
wintermute

Reputation: 130

Take a look at how the code is transpiled using babel and it becomes really clear what is happening. Using the babel console

'use strict';

var foo = { name: 'Bob', age: 24 };
var _foo = foo,
    name = _foo.name,
    age = _foo.age;


console.log(name); // 'Bob'
console.log(age); // 24

foo = { color: 'red', result: true };
var _foo2 = foo;
name = _foo2.name;
age = _foo2.age;


console.log(name); // "undefined" instead of 'red'
console.log(age); // undefined instead of true 

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

According to the MDN docs, destructuring assignment for structures is based on property names. For your second assignment, since your object doesn't have properties name and age, those variables become undefined.

If you want to rename properties when assigning to variables, you can use the following syntax:

foo = {color: 'red', result: true};
({color: name, result: age} = foo);

That will assign the color property of foo to the variable name and the result property to age.

Upvotes: 2

Related Questions