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
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
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);
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)
You can't do var 0 = "something"
so you won't be able to do that with any kind syntactical variety;