How to write better conditionals in JavaScript

Can we assign a default parameter?function test(fruit) { // printing fruit name if value provided if (fruit && fruit.

name) { console.

log (fruit.

name); } else { console.

log('unknown'); }}//test resultstest(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // appleLook at the example above: we want to print the fruit name if it’s available or we will print unknown.

We can avoid the conditional fruit && fruit.

name checking with default function parameter & destructing.

// destructing – get name property only// assign default empty object {}function test({name} = {}) { console.

log (name || 'unknown');}//test resultstest(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // appleSince we only need property name from fruit, we can destructure the parameter using {name}, then we can use name as variable in our code instead of fruit.

name.

We also assign empty object {} as default value.

If we do not do so, you will get error when executing the line test(undefined) – Cannot destructure property name of 'undefined' or 'null'.

because there is no name property in undefined.

If you don’t mind using 3rd party libraries, there are a few ways to cut down null checking:use Lodash get functionuse Facebook open source’s idx library (with Babeljs)Here is an example of using Lodash:// Include lodash library, you will get _function test(fruit) { console.

log(__.

get(fruit, 'name', 'unknown'); // get property name, if not available, assign default value 'unknown'}//test resultstest(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // appleYou may run the demo code here.

Besides, if you are a fan of Functional Programming (FP), you may opt to use Lodash fp, the functional version of Lodash (method changed to get or getOr).

4.

Favor Map / Object Literal than Switch StatementLet’s look at the example below — we want to print fruits based on color:function test(color) { // use switch case to find fruits in color switch (color) { case 'red': return ['apple', 'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; }}//test resultstest(null); // []test('yellow'); // ['banana', 'pineapple']The above code seems nothing wrong, but I find it quite verbose.

The same result can be achieve with object literal with cleaner syntax:// use object literal to find fruits in color const fruitColor = { red: ['apple', 'strawberry'], yellow: ['banana', 'pineapple'], purple: ['grape', 'plum'] };function test(color) { return fruitColor[color] || [];}Alternatively, you may use Map to achieve the same result:// use Map to find fruits in color const fruitColor = new Map() .

set('red', ['apple', 'strawberry']) .

set('yellow', ['banana', 'pineapple']) .

set('purple', ['grape', 'plum']);function test(color) { return fruitColor.

get(color) || [];}Map is the object type available since ES2015, which allows you to store key value pairs.

Should we ban the usage of switch statements?.Do not limit yourself to that.

Personally, I use object literals whenever possible, but I wouldn’t set a hard rule to block that — use whichever make sense for your scenario.

Todd Motto has an article that digs deeper on switch statements vs object literals.

You may read it here.

TL;DR: Refactor the syntaxFor the example above, we can actually refactor our code to achieve the same result with Array.

filter .

const fruits = [ { name: 'apple', color: 'red' }, { name: 'strawberry', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'pineapple', color: 'yellow' }, { name: 'grape', color: 'purple' }, { name: 'plum', color: 'purple' }];function test(color) { // use Array filter to find fruits in color return fruits.

filter(f => f.

color == color);}There’s always more than 1 way to achieve the same result.

We have shown 4 with the same example.

Coding is fun!5.

Use Array.

every & Array.

some for All / Partial CriteriaThis last tip is more about utilizing the new (but not so new) Javascript Array function to reduce the lines of code.

Look at the code below — we want to check if all fruits are in red color:const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' } ];function test() { let isAllRed = true; // condition: all fruits must be red for (let f of fruits) { if (!isAllRed) break; isAllRed = (f.

color == 'red'); } console.

log(isAllRed); // false}The code is so long!.We can reduce the number of lines with Array.

every:const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' } ];function test() { // condition: short way, all fruits must be red const isAllRed = fruits.

every(f => f.

color == 'red'); console.

log(isAllRed); // false}Much cleaner now right?.In a similar way, if we want to test if any of the fruit is red, we can use Array.

some to achieve it in one line.

const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' }];function test() { // condition: if any fruit is red const isAnyRed = fruits.

some(f => f.

color == 'red'); console.

log(isAnyRed); // true}SummaryLet’s produce more readable code together.

I hope you learned something new in this article.

That’s all.

Happy coding!.. More details

Leave a Reply