Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
if | Conditional Statements
Introduction to JavaScript
course content

Contenido del Curso

Introduction to JavaScript

Introduction to JavaScript

1. Basic Concepts
2. Variables and Data Types
3. Basic Operations
4. Conditional Statements
5. Loops
6. Functions

bookif

Conditions in JavaScript provide control over the execution flow. While the interpreter executes commands in order, programmers often need to alter this flow based on specific conditions. To achieve this, JavaScript offers two keywords: if and else.

if Statements

The if keyword allows you to open a code block that will be executed if the given condition is true:

1234567
if (true) { console.log("It's TRUE!"); } if (false) { console.log("It's FALSE!"); }
copy

In the above example, the if statement executes code only when the condition is true. The syntax of an if statement is straightforward: it begins with the if keyword, followed by the condition enclosed in parentheses (), and a code block enclosed in curly braces {}.

The opening curly brace { denotes the start of the code block, and the closing curly brace } marks its end.

An expression, as well as a value, can be considered as a condition.

1234567891011121314151617
let a = 935; if (a > 17) { console.log("The variable is greater than 17"); } if (a > 235124) { console.log("The variable is greater than 235124"); } if (a > 0) { console.log("The variable is greater than 0"); } if (a < 0) { console.log("The variable is less than 0"); }
copy

In the example above, when a = 935, there are four conditions:

ConditionCondition resultCode has been executed?
a > 17trueYes
a > 235124falseNo
a > 0trueYes
a < 0falseNo

You are not limited to performing operations solely inside the code block:

123456789101112131415
let a = 5; let b = 3; let c; if (a > 0 && b > 0) { c = a - b; console.log("c =", c); } if (a > 2 && b > 2) { c = a + b; console.log("c =", c); } console.log(a, b, c);
copy

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 1
We're sorry to hear that something went wrong. What happened?
some-alt