Learn about Conditional Statements in Javascript

In this Lecture we will discuss about conditional statements in javascript

  • if – else statement
  • switch statement
  • ternary operator

The code examples below are also available on Github

if…else

Syntax

if (condition) {
// code
} else {
// code
}

else if
To add more else conditions you can use else if clause

if (1<x<2) {

} else if (2<x<3) {

} else {

}

We can use conditional operators like <, >, <= etc.

if(x == ‘A’) {

}

From the documentation

Any value that is not false, undefined, null, 0, NaN, or an empty string (”) actually returns true when tested as a conditional statement, therefore you can simply use a variable name on its own to test whether it is true, or even that it exists (that is, it is not undefined.)

 

if (data) {
console.log(data);
}

Switch Case
If-else is good when we have few conditions to take care of. What if we want to add more conditions. Let us look at an example

let day = ‘Monday’
switch(day) {
case ‘Monday’:
console.log(‘Today is Monday’)
break;
case ‘Tuesday’:
console.log(‘Today is Tuesday’)
break;
case ‘Wednesday’:
console.log(‘Today is Wednesday’)
break;
default:
console.log(‘No Match’)
}

This example demonstrates how to use switch statements.

Ternary Operator
It’s a convenient way to write if-else in a compact manner.

Instead of writing

let x = 8

 

if(x>2) {
// print 3
} else {
// print 5
}

we can write

let x = 8
(x > 2) ? 3 : 5

Author: codesmartly

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s