If Statements: Do You Really Need Them in Your Code
While there's nothing really wrong with using if statements, it can help to avoid them when possible. Here are some examples of how to avoid If statements.
Sep 22, 2015 • 3 Minute Read
An if statement lets your program know whether or not it should execute a block of code. Comparison-based branching is a core component of programming. The concept of an if-else or switch block exists in almost every programming language. While there's nothing really wrong with using if statements, it can help to avoid them when possible.
Why, you might ask? Programming without if statements challenges you to think out of the box. You will have to learn other ways to structure your code, which may make it more readable. Plus, it can help you become more comfortable with data-driven and/or object oriented solutions.
Of course, writing without if statements might not always be the right answer. In fact, sometimes trying to avoid if statements will make the code less readable. But this exercise will help you see that there are other ways. Take a look at some examples below of code without the use of conditionals (if, switch, ternaries) to show you how to avoid if statements.
Example 1: Count the odd numbers in an arrayOfNumbers:
// Example input
let arrayOfNumbers = [1,4,5,9,0,-1,5];
// ***********
// Instead of:
// ***********
let counter1 = 0;
arrayOfNumbers.forEach(number => {
let remainder = Math.abs(number%2);
if (remainder === 1) {
counter1++;
}
});
console.log(counter1);
// ***********
// How about:
// ***********
let counter2 = 0;
arrayOfNumbers.forEach(number => {
let remainder = Math.abs(number%2);
counter2 = counter2 + remainder;
});
console.log(counter2);
In this example, we're taking advantage of the fact that the result of modulus 2 operation is always either 1 (for odd) or 0 (for even).
Example 2: Write a function that takes a date object argument, and returns the string "weekend" or "weekday"
// ***********
// Instead of:
// ***********
let weekendOrWeekday1 = inputDate => {
let day = inputDate.getDay();
if (day === 0 || day === 6) {
return "weekend";
} else {
return "weekday";
}
// Or, for ternary fans:
// return (day === 0 || day === 6) ? "weekend" : "weekday";
};
console.log(weekendOrWeekday1(new Date()));
// ***********
// How about:
// ***********
let weekendOrWeekday2 = inputDate => {
let day = inputDate.getDay();
let labels = { 0: "weekend", 6: "weekend", default: "weekday" };
return labels[day] || labels['default'];
};
console.log(weekendOrWeekday2(new Date()));
Did you notice that the if statement condition has some data in it? It tells us which days are weekends. We'll watch for this pattern, extract the data presented in the if statement into an object, and use that instead.
Example 3: (A bit more advanced) Write the function doubler; based on the type of input, it will do the following:
When the input is
- A number, it doubles it (i.e. 5 => 10, -10 => -20)
- A string, it repeats every letter (i.e. 'hello' => 'hheelloo')
- A function, it calls it twice
- An array, it calls itself on all elements of that array
- An object, it calls itself on all the values of that object
// ***********
// Instead of:
// ***********
let doubler1 = input => {
switch(typeof input) {
case "number":
return input + input;
case "string":
return input.split('').map(letter => letter + letter).join('');
case "object":
Object.keys(input).map(key => input[key] = doubler1(input[key]));
return input;
case "function":
input();
input();
}
};
console.log(doubler1(-10));
console.log(doubler1('hey'));
console.log(doubler1([5, 'hello']));
console.log(doubler1({a: 5, b: 'hello'}));
console.log(doubler1(function() { console.log('callme'); }));
// ***********
// How about:
// ***********
let doubler2 = input => {
let operationsByType = {
'number': input => input + input,
'string': input => input.split('').map(letter => letter + letter).join('');
'function': input => { input(); input(); },
'object': input => {
Object.keys(input).map(key => input[key] = doubler2(input[key]));
return input;
}
};
return operationsByType[typeof input](input);
};
console.log(doubler2(-10));
console.log(doubler2('hey'));
console.log(doubler2([5, 'hello']));
console.log(doubler2({a: 5, b: 'hello'}));
console.log(doubler2(function() { console.log('callme'); }));
Again, notice how the data (which operations should be done for which type) was all extracted out of the switch statement into an object, then the object was invoked with the correct parameter.
Now that you've seen a few examples of coding without if statements, what are your thoughts? Applied reasonably, programming without if statements can make your code better. If nothing else, it will help you see alternative solutions. And that’s a valuable skill for any coder.