The Many Faces of Javascript Conditionals

Hello, Today, we’ll be talking about conditionals in Javascript.

If you would like to have a better look at the code snippets I’ll be using throughout this tutorial, I have a link to the Github repo here.

When we write javascript code, we always have our code make a decision and then do something based on that decision.

We can have our code change the colour of a text, display a message to a user or self-destruct an application to name a few.

IF conditionals -

The popular kid in the block. If statements are the most common types of conditionals and they are quite easy to read as you can see from our example -

let mood = ‘happy’if(mood == ‘sad’){
console.log(‘Please be happy!’)
}

when you run this code on your javascript console, you can see that we have nothing output to the console but when we change the variable: mood to ‘sad’, now we have something on the console because the condition has been met.

In case you do not understand what is going on, I first declared a variable: mood and assigned a value of ‘happy’ to it and then burdened my if statement with checking if the mood is ‘sad’ and then if it is ‘sad’, I command us through the console to be happy.

IF-ELSE conditionals

That seemed pretty straight forward but, what if we want to do something if the mood isn’t sad?

What if we want to have the console print the question ‘What mood are you in?’

if(mood == ‘sad’){
console.log(‘Please be happy!’)
}else{
console.log(‘What is your mood then’)
}

Boom. All we had to do was introduce the else statement and a curly brace with a console.log enclosed within asking what mood we are in then.

You can also write this code without the curly braces like this -

if(mood == ‘sad’) console.log(‘Please be happy!’)
else console.log(‘What is your mood then’)

but this can get confusing for another developer so you should probably avoid that.

ELSE-IF

There are different kinds of moods. Someone can be happy, sad, angry or agitated.

What if we want out code to do something for all these different kinds of moods?

if (mood == ‘sad’) {
console.log(‘Please be happy!’);
} else if(mood== ‘angry’){
console.log(‘Calm down tiger’)
}else if(mood == ‘happy’){
console.log(‘Champagne anyone? What is the occasion?’)
}else if(mood == ‘agitated’){
console.log(‘Talk to me, Why are you worried’)
}
else {
console.log(‘What is your mood then’);
}

Now our code accounts for all the tyes of mood we listed and even has accommodation for moods that we have not accounted for.

But this is starting to get bulky. Imagine we have 30 different kinds of moods and we have to do something for each one. This could easily spiral out of our control and get very difficult to read.

We need to clean this up and that’s why we ‘ll be talking about switch statements next

SWITCH

switch(mood){
case ‘sad’:
console.log(‘Please be happy!’);
break;
case ‘angry’:
console.log(‘Calm down tiger!’);
break;
case ‘happy’:
console.log(‘Champagne anyone? What is the occasion?’);
break;
case ‘agitated’:
console.log(‘Talk to me, Why are you worried’)
break;
default:
console.log(‘What is your mood then’);
}

See, I told you it was cleaner. You‘ll use a switch when you have lots of options to choose from. It makes your code cleaner and it’s faster when you have lots of options otherwise the speed is negligible when compared to to the if-else.

When using the switch, don’t forget the break after every case. It is what tells your code to stop checking once a case meets the condition.

NESTED CONDITIONALS

So far we have been checking for just one thing, the mood. But what if you want to check your mood and then depending on your mood, check the food item available at home and then have your code decide what you should have for dinner?

let foodItem = ‘milk’if (mood == ‘sad’) {
if(foodItem == ‘milk’){
console.log(‘Take cornflakes’)
}else{
console.log(‘go to bed hungry’)
}
} else {
console.log(‘What is your mood then’);
}

Now, this gets even more confusing. Imagine we have to do this for every kind of mood and we have to check for a wide range of items. We’ll need logical operators.

|| — OR
&& — AND
! — NOT

So, for the code block above, we can shorten it to this code block below, which is more straightforward and easy to understand. We are asking our code to check if the mood is sad and we have milk as a food item and only if both conditions are met do we get the output asking us to take cornflakes.

if (mood == ‘sad’ && foodItem !== ‘milk’) { 
console.log(‘Go to bed hungry!’)
} else if(mood == ‘sad’ && foodItem == ‘milk’){
console.log(‘Take cornflakes’)
}else {
console.log(‘What is your mood then’);
}

But we are only checking for milk as a food item. What if we want the person to take cornflakes when he is sad and has corn or sugar or milk?

if(mood == ‘sad’ && (foodItem == ‘milk’ || foodItem == ‘sugar’ || foodItem == ‘corn’ )){
console.log(‘Take cornflakes’)
}else {
console.log(‘What is your mood then’);
}

This code block checks if the mood is sad and (&&) then also checks if the food item is any of the ones in our options (||) before giving out a response.

This works but it’s starting to look bulky and we are only checking for three items. We are breaking the DRY code — we are repeating ourself each time we check for a food item.

Imagine if we have to check for ten different items. We could do it this way but, why do it this way when we have a better way?

Array.includes()

let expectedItems = [‘sugar’, ‘milk’, ‘corn’]
if(mood == ‘sad’ && (expectedItems.includes(foodItem))){
console.log(‘Take cornflakes’)
}else {
console.log(‘What is your mood then’);
}

Now, this is a much more sexy code. it is easy to read and edit.

First, I made an array out of every food item I am expecting and then using javascript’s array. includes() method I am checking if the food item they have is enough to make a sad person take cornflakes.

TERNARY OPERATORS

I love ternary operators. The code is easy to understand although some people will not agree with me, especially when it comes to nested ternaries.

I write a lot of React JSX code and I prefer to use the ternary operators inside rather than have a function import my if-else statement if I can help it.

Ternary operators return true or false at the end of every line and it only executes the part of the code that returns true. So for our first if-else code where we were checking for the different types of moods, we can do the same using a ternary operator -

mood == ‘sad’ ? console.log(‘Please be happy!’) : mood == ‘angry’ ? console.log(‘Calm down tiger’): console.log(‘What is your mood then’)

Ternary operators ask a question and if it’s true the first part of the code is run, otherwise, the second part is run

Array.every()

All this while we have been checking for mood as a string. What if the mood is an attribute of a person? What if it’s a key in an array? What if we just have to check if someone is sad in a group and maybe output a msg?

let people = [
{name: ‘Adah’, mood: ‘Excited’},
{name: ‘pwetymala’, mood: ‘Angry’},
{name: ‘imouttanames’, mood: ‘Sad’}
]

What I would normally do is write a loop through this array and then find the person with the mood I am looking for and then output a msg. So my code would normally look something like this -

for (let i=0; i< people.length; i++){
if(people[i].mood == ‘Sad’){
console.log(`Tell ${people[i].name} to cheer up`)
}
}

There is nothing wrong with this but if all I want to know is if all the mood in my code pass the test and all I want is either a true or false then I can do all of that in two lines with array.every.

const uniformMood = (each) => each.mood == ‘Excited’;
console.log(people.every(uniformMood))

array.every takes a function that performs a check and returns true or false depending on if your array passed the test.

The expected output for our code is false because all the moods in the array of people are not ‘Excited’.

Neat right?

What if instead of checking if everything passed the test, we just want to check if some passed the test?

Array.some

I am not making this stuff up!

const someMood = (each) => each.mood == ‘Excited’;
console.log(people.some(someMood))

if at least one of the items in our array passes this test, in this case, if at least one of our moods is ‘Excited’, the console returns true.

There are a few things I would like to mention to look out for when working with conditionals.

The first is to always check for null or undefined. This is a commandment with a promise: that your code may live forever.

The second is to keep in mind that for the array methods like array.some() and array.every(), the compatibility with older browsers is not always great.

I will advise that you use caniuse.com to check if the method you decide to go with is compatible with the browsers you are targeting.

if you still do want to use it amidst compatibility issues, I wouldn’t blame you. It’s pretty neat. All you have to do is inject the polyfill for the method into your code and it still works for even the oldest browsers.

Alright friends, I hope this was helpful. If you have any questions, please leave a comment below, and I will get to it as soon as I can.

Aurevoir mes amis.

I eat. I read. I write. I code. Never in that order