We often encounter a situation where a property we're trying to extract doesn't exist in the object/array, resulting in a TypeError
(while destructuring nested objects) or being set to undefined
. While destructuring we can set a default value, which it will fallback to, in case of it not being found in the object.
var obj = {a : 1};
var {a : x , b : x1 = 10} = obj;
console.log(x, x1); // 1, 10
var arr = [];
var [a = 5, b = 10, c] = arr;
console.log(a, b, c); // 5, 10, undefined