Trace
Trace

Reputation: 18889

What is “fail-soft destructuring”?

On the Babel website, I found the following demo in the scope of destructuring:

// Fail-soft destructuring
var [a] = [];
a === undefined; 

After transpiling this piece of code with Babel, I get the following result in ES5:

"use strict";

var _ref = [];
var a = _ref[0];

What is fail-soft destructuring used for, and what is the logic behind the transpiled syntax? Why does Babel transpile the ES6 code this way, rather than just assigning undefined to the variable?

Upvotes: 0

Views: 806

Answers (1)

Dan Crews
Dan Crews

Reputation: 3627

Look what happens when you add some more to the example:

var [a, b, c] = [];

Transpiles to:

"use strict";

var _ref = [];
var a = _ref[0];
var b = _ref[1];
var c = _ref[2];

a gets the first thing, b the second, etc.

Upvotes: 1

Related Questions