JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - If...Else

The if statement

In JavaScript, the if statement is a fundamental control structure that enables you to execute different blocks of code based on whether a condition is true or false. This flexibility is essential for creating dynamic and interactive web applications.

Syntax

The syntax for an if statement is simple:

if (condition) { // block of code to be executed if the condition is true }
  • condition: An expression evaluated in Boolean context. If the condition evaluates to true, the code within the block is executed.

Example

Write a program to check if a user is old enough to vote.

Javascript
Javascript

. . . .

In this example, if the age variable is 18 or more, the message "You are old enough to vote!" is logged to the console.

The else statement

The else statement complements an if statement by specifying a block of code to be executed when the if condition evaluates to false. It acts as the default or fallback action when none of the if or else if conditions are met.

The execution flow of if...else statement is as given in the diagram below.

Image

Syntax

Follow the syntax below to use the else statement with if statement:

Javascript
Javascript
. . . .

Example

Extending the voting example, let's provide feedback if the user is not old enough to vote:

Javascript
Javascript

. . . .

Here, if age is less than 18, the message "Sorry, you are not old enough to vote." is displayed.

The else if statement

The else if statement is an extension of the if...else structure, allowing for multiple conditions to be checked in sequence. It's especially useful when you have several possible outcomes and need to test them one by one until a true condition is found.

Syntax

The else if statement allows you to test multiple conditions sequentially:

Javascript
Javascript
. . . .

Example

Let's say you're creating a grading system where grades are assigned based on the score:

Javascript
Javascript

. . . .

In this example, a score of 75 results in "Grade C". The program checks each condition in order until one is true, then executes the corresponding code block.

For practice modify the value of score to 85 or 95 and see what is printed on the console.

The if...else statement in JavaScript is a powerful tool for adding decision-making to your programs. By understanding how to use if, else, and else if statements together, you can control the flow of your code based on conditions, making your web applications more dynamic and responsive to user input.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next