[Javascript] Conversion from if statement to OR expression | Deconstruction

The following themes are newly learned features of Javascript.

Short-Circuit Evaluation and OR Expression

While using the logical operators, for instance and, or, and not, there are cases where the assessment of the second value is irrelevant. For example in OR expressions, when the first value is true, the expression is true no matter the second value of the expression. In these cases, Javascript chooses not to evaluate the second value, and this is called “short-circuit evaluation”. This is notable in that using this concept, avoiding the side effects of the second value. It is more clear in the example below.

const skip = true;
let x = 0;
const result = skip || x++; // x === 0;

In this example, the postfix increment of variable x is only executed when the value of skip is false, since when skip is true, the OR expression is true Javascript does not go through the second value of the expression.

Using this functionality of Javascript, it is possible to convert a if statement to the OR expression. The below if statement first evaluates if the options exist. When there is no options, the variable is assigned with an empty object.

if(!options) options = {};

This can be converted to the OR expression as explained above.

options = options || {};

When option is not null or undefined, options will remain the same, because Javascript skips the second value. However, when there is no valid options, Javascript will execute the second value, and assign an empty object.

Deconstruction

This is a feature introduced in ES6. Using deconstruction allows the deconstructing of objects or all iterables and assign the values into variables.

const obj = { a: 1, b: 2 };

const {a,b} = obj;

console.log(a); // 1
console.log(b); // 2

const arr = [1, 2, 3];

let [x, y] = arr;
console.log(x); // 1
console.log(y); // 2
// 3 is discarded

const arr2 = [1, 2, 3, 4, 5];

let [x, y, ...rest] = arr;

console.log(x); // 1
console.log(y); // 2
console.log(rest); // [3, 4, 5]

This can be used with functions to deconstruct the arguments passed into the function.

function deconstructEx({ a, b, c }) {
    console.log(a, b, c);
}

const o = { a: 1, b: 3, c: 5 };

deconstruct(o); // 1, 2, 3

Using this notion, it is also possible to pass a expansion operator to save all the remaining arguments into a separate array.

function addPrefix(prefix, ...words) {
    const prefixedWords = [];
    for (let i = 0; i<words.length; i++) {
        prefixedWords[i] = prefix + words[i];
    }
    return prefixedWords;
}

addPrefix("con", "verse", "vex"); // ["converse", "convex"]