# if statement

The `if` construct specifies a condition. Using this construct, we can ask the program, for example, the question "is the variable `a` greater than the variable `b`", and depending on the answer, execute one code or another.

As a rule, this construct is used in combination with the `else` construct.

## Syntax

`if (logical expression) { /* a code located here will be executed if the logical expression is true */ };`

If there is only one expression in curly braces, these curly braces can be omitted.

## Example

If the variable value is equal to one, we will display some message on the screen:

`let test = 1; if (test == 1) { alert('+++'); }`

## Example

Let's check if the variable value is greater than zero or not:

`let test = 1; if (test > 0) { alert('+++'); } else { alert('---'); }`

## Example

The `if-else` constructs can be nested in each other in an arbitrary way:

`let num = 3; if (num >= 0) { if (num <= 5) { alert('less than or equal to 5'); } else { alert('greater than 5'); } } else { alert('less than zero'); }`

## See also

- the `else` statement
  that sets an opposite condition
- the `elseif` statement
  that also sets a condition
- the `switch` statement
  that also sets a condition

↑
en ru