JavaScript Conditional Statements Tutorial

JavaScript Conditional Statements Tutorial

Following on from the epic tutorial on JavaScript Arrays and Loops, this is a much shorter one to give you a breather! In that tutorial we were using what are called JavaScript Conditional Statements – i.e. we want to perform certain actions based on defined conditions. One condition was the value of action. If action was ‘Shuffle’ we performed one block of code, if action was ‘Hit Me’, we performed a different block of code.

Simple Conditional – JavaScript if() Statement

To check if a condition is met we use a, if(){ } clause. What code’s in between the ()‘s is your condition. Take this simple example:

what_day_is_it = "Friday";if(what_day_is_it == "Friday"){ alert("Yay! It is nearly the weekend!");}

We assign the word ‘Friday’ to the variable what_day_is_it. Then if that variable is ‘Friday’ we pass out a simple alert() to declare that it is nearly the weekend.

How to Evaluate Conditions

There are different ways to evaluate conditions:

  • Does one valus equal another? Then you need to use ==. This must be a double equals. A = assigns a value, whereas a == evaluates a condition.
  • Is one value less than another? Then you need to use <. – e.g. if(x < y) would ask if x is less than y
  • Is one value greater than another? Then you need to use >. – e.g. if(x > y) would ask if x is greater than y
  • To see if one value is less than or equal to another, you use <= – e.g. if(x <= y) would ask if x is less than or equal to y
  • To see if one value is greater than or equal to another, you use >= – e.g. if(x >= y) would ask if x is greater than or equal to y
  • To ask if one value does not equal another you need to use !=. Example of this below.
what_day_is_it = "Thursday";if(what_day_is_it != "Friday"){ alert("Boo! The weekend is miles away!");}

So this time what_day_is_it is set to ‘Thursday’. Then if what_day_is_it is not “Friday” we output a message.

Understanding the Response of a Conditional Statement

JavaScript Conditional Statements give a ‘hidden’ value to determine if the condition is met. This is in the form of ‘True or False’ (alternatively 1 or 0 respectively). In programming terms this is called a Boolean. If a condition is met then the conditional statement returns True. If a conditional is not met, then the statement returns False. This does not need to be programmed in, as it is handled automatically. But it’s important you know what’s going on behind your if() statements.

What if a Condition Is Not Met?

With the two code snippets above, if the condition is not met, the nothing happens. The code does nothing and the user does not know that nothing has happened! When writing the functions in JavaScript you must always keep the user informed about what’s going on.

If your condition is not met then we need to use an else{} statement. Let’s extend the snippet above with an else{ } statement and see what happens.

what_day_is_it = "Thursday";if(what_day_is_it != "Friday"){ alert("Boo! The weekend is miles away!");}else{ alert('Yay for Friday! The Weekend is nearly here!');}

Depending on what value you give to what_day_is_it will yield one of two outputs. If that variable does not equal “Friday” then one alert() is put out. If that condition is not met (which in this case means if what_day_is_it does equal “Friday”) then a separate message is given. That means regardless of the outcome, the user is told something.

More than One Condition

Not many conditional statements have one condition to be met. In the next lesson we will be looking at Basic Form Validation. When users can put what they want into a form, you will rarely get one type of result.

To test multiple conditions you can use the else if(){ } statement. Bear in mind though if you have an else if(){ } you must end your set with an else{ } condition:

if(CONDITION 1){ // do something}else if(CONDITION 2){ // do something else}else if(CONDITION 3){ // do another thing}else{ // if none of the above are TRUE then do this.}

Evaluating More Than One Condition at Once

You might want to create a rule which asks two questions at once. Say you had an organisation that was aimed at 20-30 year olds. You want want to know whether the new member’s age was greater than or equal to 20 and less than or equal to 30. This is how you achieve that:

if(member_age <=20 && member_age>30){ alert('You are a valid member age!');}else{ alert('We are sorry but you cannot join our organisation');}
  • To see if multiple conditions are all met then you need to use && (which means ‘AND’) between each condition.
  • To check that one of your rules is met you can use || (which means ‘OR’).

Nested Rules

Going one step further, if our organisation is a ladies-only organisation for women who are ages 20-30. You can end up with

  • Men who try to apply
  • Women who try to apply but are either younger than 20 or older than 30.
  • Women who apply and are age 20-30

In this case you can nest each rule within a set of brackets: (). This works like:

if((condition 1) && (condition 2 && condition 3))

if(member_gender=="female" && (member_age <=20 && member_age>30){ alert('You are a valid member age and gender');}else if(member_gender=="male"){ alert('Apologies but our organisation is for ladies only.');}else{ alert('We are sorry but you are not the right age to join us.');}

With our ‘TRUE/FALSE’ outcomes we want to know:

  1. does member_gender == "female" AND
  2. is member_age>=20 && member_age<=30

You can use AND (&&) and OR (||) within each nested statement as well.

JavaScript Prompt in Google Chrome
JavaScript Prompt in Google Chrome

Aside: A Simple Prompt for Input From the User

As this doesn’t really warrent a whole lesson, JavaScript gives you a really easy way to ask for user for text input – via the prompt() function. You can then assign what they put in to a variable.

ask_the_user = prompt('What day is it today?');

If they put something in then ask_the_user is given that value. If they don’t (i.e. they try to press ‘OK’ without putting something in) or if they press ‘CANCEL’ then you can use an if() statement to catch that.

A Working Example of JavaScript Conditional Statements

In so-called ‘Western Culture’ we love to celebrate the weekend, so let’s create a simple script to help people celebrate. We will ask the user to tell us what the day of the week it is and then use our conditional statements to output an appropriate message.

In this example, we will be using code from our JavaScript Arrays lesson to provide a list of days which are valid to check against.

<script type="text/javascript"> function whatDayIsIt(){  var ValidDays = new Array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');  ask_the_user = prompt('What day is it today?');  day_of_the_week_number = ValidDays.indexOf(ask_the_user);  if(day_of_the_week_number<0){   alert('You have not entered a valid day. Please check and try again. Your day must start with a capital letter.');   whatDayIsIt();  }  else{   if(ask_the_user=="Friday"){    alert('Yay! It is nearly the weekend!');   }   else if (ask_the_user=="Saturday" || ask_the_user == "Sunday"){    alert('Enjoy the Weekend!');   }   else{    day_of_the_week_number+=1;    day_weekend_starts = 6;    days_until_the_weekend = day_weekend_starts - day_of_the_week_number;    alert('Do not fret! Only '+days_until_the_weekend+' days until the weekend!');   }  } }</script>

If you look over the lesson on Arrays you will be able to work through this in a logical way. What we have done here is

  • Ask the user for the day of the week: remember they could put anything in this box (not necessarily a day of the week!)
  • We grab the number of that day from the Array (remember ‘Monday’ is the first item and is therefore index 0 – this is important!)
  • Then we check if day_of_the_week_number is a valid number. If the text put in is not in our array, the indexOf() function will return -1, which is why we can use if(day_of_the_week_number<0). We could have also used if(day_of_the_week_number==-1). Both are valid.
  • The last bit of code does a quick calculation to see if it isn’t Friday, Saturday or Sunday, how many days are left until the weekend.

TL;DR – JavaScript Conditional Statements

Hopefully now you can look back at the epic card game from the last lesson and understand it a bit more. Using JavaScript Conditional Statements you can evaluate anything – whether it’s the result of a sum, a Math.random(), user input and, as we shall see next, form fields. The if-else method is one of the longest-standing programming logics. Make your own scripts using conditional statements. You could even extend the card game ’21’ with other conditions – such as adding a Joker in and making that end the game!

Spread the Word

Share This On FacebookShare This On TwitterShare This On LinkedinShare This On Google PlusShare This On PinterestShare This On Mail