Conditional Statements in JavaScript-JavaScript tutorials for beginners

by

Posted on 08 April 2017

In the previous chapter we have seen various operators in JavaScript, in this chapter we will see how to put them to good use. Conditional Statements enable you to make use of the mathematical, comparison and logical operators because they enable you to specify in your code that an action should occur only when a condition is met(conditional statements).

[Chapter -1]Introduction to JavaScript-JavaScript tutorials for beginners
[Chapter -2]Variables in JavaScript-JavaScript tutorials for beginners
[Chapter-3]JavaScript Operators-JavaScript tutorials for beginners

In order to use conditional statements we must know what they are ? And how they are useful?

What is a Conditional Statement ?

In the previous chapters we work with some simple statements, but what if we want to take some decisions in our script for example if a variable x has a value greater than 10 than only we have to alert a certain message otherwise not. We can make these types of decisions using the Conditional Statements.

Let us take a simple example from our daily life.

"If you eat a lot of junk food you will get sick. Otherwise you will stay healthy."

In the above statement there is one condition which is "eating junk food" and two actions "getting sick" and "staying healthy". This is a simple example how we decide things on the basis of a single condition.

"If i have money greater than 1000 go for shopping. Otherwise stay at home."

Try it: In the above statement try to find the condition and the two possible actions.

We can create such conditions in our scripts too, as it enable us to do quite a bit more in our scirpts.

Some more examples

  • if a variable named "name" is equal to shibli(recall how we campare two values using the ==operator), then write message saying "hello shibli".
  • If the variable named car is equal to mustang than write an output as "cool car".

Using Condtional Statements

Now you know what conditional statements are, it's time to see how to code them in your script

Using if/else statement block

The first line of the if/else block is the JavaScript key word "if", the syntax of the if statement is shown below

if(condition){
//JavaScript Statements here
}

lets see a simple example

var x = 100;
if(x > 50){ // statement is true
document.write("if statement executed");
}

In the above script we used an if statement which is having a condition (x > 50) and the value of x is 100 so the condition becomes true and the if block gets executed

Try it: In the above statement try to not to execute the if statement(hint: use the "<" operator)

Now we have seen that how to execute a statement when a given condition is true but what to do if it is false for that we have else block, below is the compelete syntax of if/else block

if(condition){
//this part gets executed if the condition is true
}
else{
//this part gets executed if the condition is false
}

let's take a simple example

var x = 10
if(x==9){
document.write("The value is 9");
}
else{
document.write("The value is not 9");
}

In the above script the else part will be executed as the condition (x==9) is false.

You can try some more examples using the if/else block by using different operators inside the conditions.

Nested if/else statements

We can use an if/else statement inside an if/else statement but you must be thinking what is the need of doing so, just take a look at the below example

if i have a car and if it is a mustang then print "cool car" else print "you have a car but its not a mustang". Let's try to convert this into a script

var haveCar = true;		//bool variable refer chapter 2 for more details
var car = “mustang”;
if(haveCar==true){		//condition true
	if(car==”mustang”){	//condition true
		document.write(“cool car”);	//this statement will be printed
	}
	else{
		document.write(“you have a car but its not a mustang”);
	}
}
else{
	document.write(“You do not have a car”);
}

In the above script you can see how a condition can have another condition inside it this is known as nesting.

Try it: In the above statement try to put an if/else block inside the parent else statement(maybe you do not have a car but you may have a bike)

Complex Comparisons

Uptil now we only see some simple conditions but we can have some complex conditions for example you will buy a computer with an 8gb ram and a core i7 processor, so the condition is you will buy the computer only if it has both the specified things(which operator we can use to check if both the conditions are true or not) see the below statement for the above statement.

if(ram=="8gb" && processor=="i7"){
document.write("My dream PC");
}
else{
document.write("lets try another shop");
}

Above is an example of a complex condition, you can code your own using the logical operators, for more about operators refer chapter-3.

The Switch Statement

The switch statement allows you to take a single variable value and execute a different block of code based on the value of the variable. If you wish to check for a number of different values, this can be an easier method than the use of a set of nested if/else statements.

The syntax of switch statement is shown below.

switch(varname){
case "testcase1":
//javaScript statements
.......
break;

default: //default statement gets executed when no match is found
.......
break;
}

Lets quickly see an example based on the switch statement.

var myName = “shibli”;
switch(myName){
	case “george”:
		document.write(“my name is george.”);
		break;
	case “shibli”:
		document.write(“my name is shibli”); // this statement gets executed
		break;
	default:
		document.write(“No name matched”);
		break;
}

In the above example you can have as much cases as much as you want, did you notice that "break" keyword, what is that? do'nt worry we will learn about it in the next chapter.

Using the conditional operator

The conditional operator(?:) often called the ternary operator is a JavaScript operator used as a short way to assign a value based on a condition. We did not discuss it in Chapter-3 because of it's relationship with conditional statements.

Syntax for conditional operator

(condition)?(//if true this block executes):(//if false this block gets executed)

lets see an example

var x = 100;
var y = (x>50)?(x):(50);
document.write(y);

The ouptut of the code will be 50 as the value 50 is assigned to the variable y on line 3 using the conditional operator.

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don't forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.


If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts

Search
Adverstisement
Adverstisement