Royi Namir
Royi Namir

Reputation: 148524

Spotting the implicit coercion?

Looking at this destructuring assignment ( ES6) :

var {a, b} = {a:1, b:2}
console.log(b); //2

It is clear that a will be 1 and b will be 2.

Babel treats it as :

"use strict";
var _a$b = { a: 1, b: 2 };
var a = _a$b.a;
var b = _a$b.b;
console.log(b);

OK.

But looking at this code :

var { x : { y = 10 } } = { x : 15 };
console.log(y); //10

As you can see the result is 10. According to Kyle Simpson , there is an implicit coercion here.

Question:

What is the implicit coercion that happens here and why/how does y is 10 ?

Upvotes: 1

Views: 77

Answers (1)

Bergi
Bergi

Reputation: 664579

This is destructuring with a default initialiser. What happens is:

  1. The {x: 15} object is destructured on the expression {x: …}
  2. The x property is matched
  3. The value 15 is destructured on the expression {y = 10} (shorthand for {y: y = 10}). For this, it is implicitly coerced to an object - like new Number(15)
  4. the y property cannot be matched, because Numbers don't have one - so the default value is taken and the initialiser is evaluated (to 10)
  5. The value 10 is assigned to the y variable.

You can also try changing the y to a property that exists on Number.prototype for a different result.

Upvotes: 6

Related Questions