Course Content
Introduction to JavaScript
Introduction to JavaScript
if
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
:
if (true) { console.log("It's TRUE!"); } if (false) { console.log("It's FALSE!"); }
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.
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"); }
In the example above, when a = 935
, there are four conditions:
Condition | Condition result | Code has been executed? |
a > 17 | true | Yes |
a > 235124 | false | No |
a > 0 | true | Yes |
a < 0 | false | No |
You are not limited to performing operations solely inside the code block:
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);
Everything was clear?