ECMAScript if Statement

The if statement is one of the most commonly used statements in ECMAScript.

ECMAScript Statements

ECMA-262 describes several types of statements (statement) in ECMAScript.

Statements mainly define most of the ECMAScript statements, usually using one or more keywords to complete the given task.

Statements can be very simple, such as notifying a function to exit, or very complex, such as declaring a set of commands to be executed repeatedly.

In this chapter "ECMAScript Statements", we introduce all the standard ECMAScript statements.

if statement

The if statement is one of the most commonly used statements in ECMAScript, and in fact, it is so in many computer languages.

Syntax of if statements:

if (condition) statement1 else statement2

where condition It can be any expression, and the result of the calculation does not have to be a true boolean value, ECMAScript will convert it to a boolean value.

; If the condition evaluates to true, then execute statement1; If the condition evaluates to false, then execute statement2.

Each statement can be a single line of code or a code block.

For example:

if (i > 30)
  {alert("Greater than 30");}
else
  {alert("Less than or equal to 30");}

Tip:Using code blocks is considered the best programming practice, even if the code to be executed is only one line. This makes it clear what each condition is supposed to do.

You can also chain multiple if statements. Like this:

if (condition1) statement1 else if (condition2) statement2 else statement3

For example:

if (i > 30) {
  alert("Greater than 30");
}
  alert("Less than 0");
}
  alert("Between 0 and 30");
}