6

code:

const x = 6;
const ob = {x: [6.1, 6.5]} 
console.log(ob) // {x: [6.1, 6.5]}

const y = 6;
const ob = {[y] : [6.1, 6.5]};
console.log(ob) // {6: [6.1, 6.5]}

Why square brackets allow use the value of the variable as object key, is this related to destructuring??

3
  • 1
    It's a special type of syntax known as computed property names. See: What do square brackets around a property name in an object literal mean? Commented Jul 7, 2020 at 3:46
  • 1
    thanks for that info, Commented Jul 7, 2020 at 3:47
  • 2
    It's not related to destructuring. In your first example, the two "x"s have nothing to do with each other (the const x line is unused). The syntax ob["foo"] is the same as ob.foo, but you can only use the latter syntax because "foo" is a valid identifier. You could use ob["foo-bar"] but not ob.foo-bar. The bracket syntax also allows you to use a property where you don't know the key at compile time, eg const key = calculateKey();ob[key] Commented Jul 7, 2020 at 3:52

1 Answer 1

4

The square brackets allow for computed property keys. In other words, the value of the variable inside of the square brackets is processed before the value is accessed.

Sign up to request clarification or add additional context in comments.

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.