Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 388
Luka Prebil Grintal Avatar asked Jun 28 '21 14:06

Luka Prebil Grintal


1 Answers

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.

like image 122
CertainPerformance Avatar answered Sep 22 '22 19:09

CertainPerformance