If you are working with JavaScript, you would be writing a lot of code with a lot of conditions involved. At first, conditionals may seem easy to learn, but there is more to it than to write a few if-else statements.
Object-oriented programming allows one to avoid conditions and replace them with polymorphism and inheritance. You should follow these principles as much as possible. But on the other side, you may end up with the conditionals in your code for various reasons. This article’s purpose is to help you organize the conditional statements.
Tips for writing code with conditionals:
-
Array.includes: You can use array.includes() method for multiple conditions. The array.includes() method is used to determine if a particular element is present in the array. It returns “true” or “false”
Example: The following code demonstrates, how to check if the animal is a “lion” or a “dog”.
Javascript
// function
function
test(animal) {
if
(animal ==
'Lion'
|| animal ==
'dog'
) {
console.log(
'Valid'
);
}
}
// function call
test(
'dog'
);
Output:
Valid
The above code seems to be easy because you have only two animals to check for. However, you are not sure about the input of the user. What if you get a few more animals? If you keep expanding the statement with more OR statements, the code would be more difficult to maintain and looks very unclean.
You can rewrite the function to make it cleaner. All you need to do is add a new array item if you want to check for some other animal.
Javascript
function
test(animal) {
const animals = [
'dog'
,
'cat'
,
'cow'
,
'Lion'
];
// Used to check if a particular
// element is present
if
(animals.includes(animal)) {
console.log(
'valid'
);
}
}
console.log(test(
'dog'
));
Output:
valid
You can create an array of animals to separate the conditions from the rest of the code. You can even declare the variable out of the scope of the function and reuse it wherever you need it. This is a way to write a cleaner code that is easy to understand and maintain.
-
Array.every & Array.some:
array.every() method is used to check if all the elements present in the array satisfies the given condition. It returns “true” when each array element satisfies the given condition otherwise it returns “false”.
array.some() method checks if any of the elements in the array have passed the test of function provided. The array.some() method executes the function once for every element of the array. It checks if at least one of the elements of the array satisfies the condition.
These two JavaScript Array functions are used to reduce the lines of code. Look at the code given below.
Javascript
// Array of objects
const cars = [
{ name:
'car1'
, color:
'red'
},
{ name:
'car2'
, color:
'blue'
},
{ name:
'car3'
, color:
'purple'
}
];
function
test() {
let isAllblue =
true
;
// Condition: all cars must be blue
for
(let c of cars) {
if
(!isAllblue)
break
;
isAllblue = (c.color ==
'blue'
);
}
console.log(isAllblue);
}
test();
Output:
false
The above code is little lengthy. You can reduce it by using Array.every() method.
Javascript
// Array of objects
const cars = [
{ name:
'car1'
, color:
'red'
},
{ name:
'car2'
, color:
'blue'
},
{ name:
'car3'
, color:
'purple'
}
];
function
test() {
// Condition: short way
// all cars must be in blue color
const isAllblue = cars.every(
c => c.color ==
'blue'
);
console.log(isAllblue);
}
test();
Output:
false
You can also implement it using Array.some() method
Javascript
// Array of objects
const cars = [
{ name:
'car1'
, color:
'red'
},
{ name:
'car2'
, color:
'blue'
},
{ name:
'car3'
, color:
'purple'
}
];
function
test1() {
// Condition: if any car is in blue color
const isAnyblue = cars.some(c => c.color ==
'blue'
);
console.log(isAnyblue);
}
test1();
Output:
true
-
Return Early or Early exit: The Return Early in JavaScript is an easy way to reduce a function body to zero the number of “else” statements. There are many reasons to use Return Early in your code.
- It reduces the total amount of code.
- It reduces the length of the line by reducing the logical complexity.
- It helps to improve readability.
The purpose of the Return early is to eliminate the need for “else” conditionals in JavaScript functions by using the “return” keyword in the “if” statement of the body. Let us create a function that will behave differently within certain conditions.
Note: The following demonstrates the pseudocode for the above explanation.
Javascript
function
IsRed(someObject) {
// Declare a variable to
// store the final value
var
willRed;
// Compare type of object
if
(
typeof
someObject ===
'object'
) {
// Check object color property
// is red or not
if
(someObject.color ===
'Red'
) {
willRed =
true
;
}
else
{
willRed =
false
;
}
}
else
{
willRed =
false
;
}
return
willRed;
}
This function is clear, but it seems to be unnecessarily complicated. The Return early pattern can be used to increase readability and decrease the number of “else” statements.
Javascript
// Use return instead of else statement
function
IsRed(someObject) {
if
(
typeof
someObject !==
'object'
) {
return
false
;
}
if
(someObject.color !==
'Red'
) {
return
false
;
}
return
true
;
}
Using the Return Early pattern, we are able to eliminate all the unnecessary “else” statements and make your functions much clearer and concise.
You can also refactor this function by using only one “if” statement.
Javascript
// Here you can reduce your code
function
IsRed(someObject) {
// 2 if statements replaced
// by 1 if statement
if
(
typeof
someObject !==
'object'
||
someObject.color !==
'Red'
) {
return
false
;
}
return
true
;
}
This function can be refactored again in a single line of code by using a ternary operator of JavaScript.
Javascript
function
IsRed(someObject) {
return
typeof
someObject !==
'object'
|| someObject.color !==
'Red'
?
false
:
true
;
}
You reduced all the nesting “if” statements, by reducing the conditions.
Note: Always aim for lesser nesting and Return Early but don’t spoil it. If your code is short and straight-forward, and if it is clearer with nested “if”s.
-
Use Object Literal or Maps: The object literal is basically an array of key:value pairs which are used instead of switch statements. Let us look at the example below.
Javascript
function
printCars(color) {
// Use switch case to
// find cars by color
switch
(color) {
case
'red'
:
return
[
'Rcar1'
,
'Rcar2'
];
case
'blue'
:
return
[
'Bcar1'
,
'Bcar2'
];
case
'purple'
:
return
[
'Pcar1'
,
'Pcar2'
];
default
:
return
[];
}
}
printCars(
null
);
printCars(
'blue'
);
Output:
[] ['Bcar1', 'Bcar2']
The above code can be refactored by using object literal and replacing the “switch” statement totally.
Javascript
// Use object literal to
// find cars by color
const carColor = {
red: [
'Rcar1'
,
'Rcar2'
],
blue: [
'Bcar1'
,
'Bcar2'
],
purple: [
'Pcar1'
,
'Pcar2'
]
};
function
printcars(color) {
return
carColor[color] || [];
}
console.log(printcars());
console.log(printcars(
'red'
));
console.log(printcars(
'blue'
));
Output:
[] ['Rcar1', 'Rcar2'] ['Bcar1', 'Bcar2']
You can also use Map to achieve the same result.
Javascript
// Use map to find cars by color
const carColor =
new
Map()
.set(
'red'
, [
'Rcar1'
,
'Rcar2'
])
.set(
'blue'
, [
'Bcar1'
,
'Bcar2'
])
.set(
'purple'
, [
'Pcar1'
,
'Pcar2'
]);
function
printcars(color) {
return
carColor.get(color) || [];
}
console.log(printcars());
console.log(printcars(
'red'
));
console.log(printcars(
'blue'
));
Output:
[] ['Rcar1', 'Rcar2'] ['Bcar1', 'Bcar2']
-
Use Default Function parameters and Destructuring: The default parameter is a way to set default values for parameters of function in which a value is not passed in i.e. “undefined”.
Javascript
function
check(flower, quantity) {
if
(!flower)
return
;
// If quantity not provided,
// set default to one
const a = quantity || 1;
console.log(
"I have ${a} ${flower}!"
);
}
// Results
check(
'Rose'
);
check(
'Lotus'
, 2);
Output:
I have 1 Rose! I have 2 Lotus!
Now you can use function parameter to set the default value
Javascript
// If quantity not provided, parameter
// provided to set default to one
function
check(flower, quantity = 1) {
if
(!flower)
return
;
console.log(`I have ${quantity} ${flower}!`);
}
// Results
// (Default parameter is set)
check(
'Rose'
);
check(
'Lotus'
, 2);
Output:
I have 1 Rose! I have 2 Lotus!
What if flower variable is an object? Can you assign the default parameter to it?
Javascript
function
check(flower) {
// Print flower name if
// value provided
if
(flower && flower.name) {
console.log(flower.name);
}
else
{
console.log(
'unknown'
);
}
}
// Results
check(undefined);
check({});
check({ name:
'Rose'
, color:
'red'
});
Output:
unknown unknown Rose
In the above example, we want to print the “flower” name if it is available else it will print “unknown”, if the value is not known. We can avoid the conditionals “flower” and “flower.name” by using default function parameter destructing.
Destructuring allows you to extract properties from objects.
Javascript
// Destructing access name property only
// assign the default empty object {}
function
check({name} = {}) {
console.log (name ||
'unknown'
);
}
// Results
check(undefined);
check({ });
check({ name:
'Rose'
, color:
'red'
});
Output:
unknown unknown Rose
We need property name from flower, you can destructure that parameter using {name}, then use name as variable in your code instead of flower.name because destructuring allows you to assign the properties of an object to the variables.
You also need to assign empty object {} as default value. If you don’t, it will show the error while executing the line “check(undefined)” i.e. cannot destructure the property name of ‘undefined’ or ‘null’, because there is no name property in undefined or null.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!