0

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

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.