Mark As Completed Discussion

If-Else Statements

In JavaScript, the if-else statement is a control flow statement that allows you to handle alternative conditions. With if-else statements, you can define two blocks of code to be executed depending on whether a condition is true or false.

The basic syntax of an if-else statement is as follows:

JAVASCRIPT
1if (condition) {
2  // code to execute if condition is true
3} else {
4  // code to execute if condition is false
5}

Let's take an example to understand the usage of if-else statements. Imagine we have a variable age with a value of 25, and we want to check if the person is eligible to vote based on their age:

JAVASCRIPT
1const age = 25;
2
3if (age < 18) {
4  console.log('Sorry, you are not eligible to vote.');
5} else {
6  console.log('You are eligible to vote!');
7}

In this example, we first check if the age is less than 18. If the condition is true, the message 'Sorry, you are not eligible to vote.' will be logged to the console. If the condition is false, the code inside the else block will be executed, and the message 'You are eligible to vote!' will be logged.

The if-else statement is a powerful tool for handling alternative conditions in JavaScript. It allows your code to make different decisions based on different scenarios, providing flexibility and adaptability to your programs. You can have multiple else if blocks to handle more conditions if needed.

Try the following code snippet and observe the output:

JAVASCRIPT
1const num = 10;
2
3if (num % 2 === 0) {
4  console.log('The number is even');
5} else {
6  console.log('The number is odd');
7}
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment