Back to course

Control Flow: Introducing the 'if' statement

JavaScript: The Complete '0 to Hero' Beginner Course

32. Control Flow: The if Statement

Control flow refers to the order in which individual statements, instructions, or function calls are executed. The most fundamental control flow tool is the if statement, which allows code to run only if a condition is true.

Syntax

javascript if (condition) { // Code inside the curly braces runs ONLY if the condition is true }

// Code outside the braces runs regardless of the condition

Example

javascript let temperature = 35;

if (temperature > 30) { console.log('It is extremely hot outside!'); }

console.log('Finished checking temperature.');

// Output: // It is extremely hot outside! // Finished checking temperature.

Truthiness in if

Remember that JS uses truthy/falsy values for the condition check.

javascript let userName = 'Charlie'; // A non-empty string is Truthy

if (userName) { console.log(Hello, ${userName}.); }

let count = 0; // 0 is Falsy

if (count) { console.log('This will not run.'); }