Here are some exercises and examples that can help you practice using if
statements in JavaScript:
- Write a program that checks if a number entered by the user is even or odd. If the number is even, print “The number is even.” If the number is odd, print “The number is odd.”
let number = parseInt(prompt("Enter a number:"));
if (number % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
- Write a program that checks if a number entered by the user is positive, negative, or zero. If the number is positive, print “The number is positive.” If the number is negative, print “The number is negative.” If the number is zero, print “The number is zero.”
let number = parseInt(prompt("Enter a number:"));
if (number > 0) {
console.log("The number is positive.");
} else if (number < 0) {
console.log("The number is negative.");
} else {
console.log("The number is zero.");
}
- Write a program that checks if a year entered by the user is a leap year. If the year is a leap year, print “The year is a leap year.” If the year is not a leap year, print “The year is not a leap year.”
let year = parseInt(prompt("Enter a year:"));
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
console.log("The year is a leap year.");
} else {
console.log("The year is not a leap year.");
}
- Write a program that checks if a letter entered by the user is a vowel or a consonant. If the letter is a vowel, print “The letter is a vowel.” If the letter is a consonant, print “The letter is a consonant.”
let letter = prompt("Enter a letter:").toLowerCase();
if (letter === "a" || letter === "e" || letter === "i" || letter === "o" || letter === "u") {
console.log("The letter is a vowel.");
} else {
console.log("The letter is a consonant.");
}
These exercises are just a starting point and can be modified to suit your needs. The goal is to practice using if
statements to make decisions based on different conditions.
+ There are no comments
Add yours