If-Else Statement in JavaScript

In JavaScript programming language, If-Else statement is widely used to make a decision in programming. Let’s just understand it with a simple example. A programmer is coding a program and he has got to code for login sign up page. Now based on the credentials the user has submitted the programmer has to decide whether what function has to be performed when the user inputs all the necessary details of him or her.
If the user has input the correct details of it’s login send the under or redirect the user to the dashboard page or else if the details are incorrect restrict the user to the login page.
This is how the If-Else statement works in JavaScript programming language. If the statement is true then go to this or else go to this. Keep one thing clear in your mind that in if-else statement only one among the mentioned statement works. Either if will work or if IF statement is false then else statement will execute.
Thus, here comes the usage of comparison operator. (we have already covered comparison operators in another blog. Click to view). Assignment Operators are used in IF statements to check whether the compared values are true or not.
We would try to understand this with the help of code.

Example of Code:
x=5 // assigned a value to x
y=5 // assigned value to y

if (x==y) // using comparison operator to check if the comparison is true or not
console.log(“Values are correct“) //run this block of code if statement is true
Console.log(“Values are incorrect”)

Similarly, let’s check it out with another example that better implies the good use of else statement in if else statement.
x=10 // assigned value to x
y=6 // assigned value to y

if(x==y) //Comparison operator to see if the statement is true or not
//if the statement is true run the block of code below otherwise go directly to else statement

console.log(“The values are equal”)

console.log(“values are not equal”)

values are not equal

in IF-Else statement we do not only use the equals to comparison operator rather we are always open to use any sort of comparison operator which fulfils our need.
For example, I want to register the only students whose ages are less than 20. Now, I would use the comparison operator < (less than operator) to perform my required task. It would be very easy for me to handle this. I would allow every user to input his or her age and I will use If-else statement to just consider only those with the ages less than 20.

For your Practice

Question: Write a simple program using If-else statement to print the message on screen “I love JavaScript” if a is greater than b. If a is not greater than b you have to print the output “I am learning JavaScript”. a=3 and b=4.
Submit your solutions below in comment section


1 thought on “JavaScript IF-ELSE Statement

Leave a Reply

Your email address will not be published. Required fields are marked *