Search code examples
javascriptdestructuringlanguage-features

Why does JS desctructuring assignment work with numbers


As the title says, why does this code not throw a SyntaxError? I thought you could only destructure Objects

const {
  a,
  b
} = 0;

console.log(a, b); // undefined, undefined


Solution

  • When you access a property of a primitive, the primitive's object wrapper is used to see if such a property exists on the prototype. For example, Number.prototype.toFixed exists. So you could theoretically do something like

    const {
      toFixed
    } = 0;
    
    console.log(toFixed);

    or

    Number.prototype.a = 'foo'; // just for example, please never do this
    Number.prototype.b = 'bar';
    
    const {
      a,
      b
    } = 0;
    
    console.log(a, b);

    It's not invalid syntax, it's just really weird.