-1

Can I destructure a property named after an integer, on an object?

const { 0 } = { ['0']: 'foo' } // doesn't work

// or

const arr = ['foo']
const { 0, length } = arr // doesn't work
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 1
    MDN also has an example for properties that would be invalid identifiers -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Invalid_JavaScript_identifier_as_a_property_name – Andreas Mar 07 '20 at 12:04

3 Answers3

5

0 is not a valid identifier (variable name). You'll have to put it into some other variable name instead:

const { 0: containsFoo } = { ['0']: 'foo' };
console.log(containsFoo);

const arr = ['foo'];
const { 0: containsFoo, length } = arr;
console.log(containsFoo);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Yes, but you must supply a name for the property to be destructured into because an integer is not a valid identifier. For example:

const { 0: zero } = { ['0']: 'foo' }
console.log(zero)

and,

const arr = ['foo']
const { 0: zero, length } = arr
console.log(zero, length)

This is useful for methods like String#matchAll:

const matches = 'foo'.matchAll(/o/gi)
for(let {0: item, index} of matches)
    console.log(item, index)
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
0

You can't do var 0 = "something" so you won't be able to do that with any kind syntactical variety;

Mechanic
  • 5,015
  • 4
  • 15
  • 38