JavaScript if else statement is a conditional statement that allows you to execute different blocks of code depending on whether a certain condition is true or false. In this tutorial, we will do if…else example programs using JS.
For example flow:
- You start with the keyword
if
, followed by a condition that you want to check. - If the condition is true, the block of code inside the curly braces
{}
after theif
statement will be executed. - If the condition is false, the program will skip the
if
block and move on to theelse
block. - The
else
block starts with the keywordelse
, followed by the block of code inside curly braces{}
that should be executed if the condition is false.
JavaScript if…else example programs example
Simple example code of JavaScript programs that use the if…else statement.
1. Checking if a number is positive or negative
<!DOCTYPE html>
<html>
<body>
<script>
let num = -5;
if (num >= 0) {
console.log("The number is positive");
} else {
console.log("The number is negative");
}
</script>
</body>
</html>
Output:
2: Checking if a password is valid
let password = "mypassword123";
if (password.length >= 8 && password.includes("$")) {
console.log("The password is valid");
} else {
console.log("The password is invalid");
}
3. Checking if a number is even or odd
let num = 7;
if (num % 2 === 0) {
console.log("The number is even");
} else {
console.log("The number is odd");
}
4. Checking the highest number
let num1 = 10;
let num2 = 5;
if (num1 > num2) {
console.log(num1 + " is the highest number");
} else {
console.log(num2 + " is the highest number");
}
5. Checking if a year is a leap year
let year = 2024;
if (year % 4 === 0) {
if (year % 100 === 0) {
if (year % 400 === 0) {
console.log(year + " is a leap year");
} else {
console.log(year + " is not a leap year");
}
} else {
console.log(year + " is a leap year");
}
} else {
console.log(year + " is not a leap year");
}
6. Checking if a string is a palindrome
let str = "racecar";
let reversedStr = str.split("").reverse().join("");
if (str === reversedStr) {
console.log(str + " is a palindrome");
} else {
console.log(str + " is not a palindrome");
}
Do comment if you have any doubts or suggestions on this Js if else practice code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version