Back to course

Control Flow: The 'if...else' Structure

JavaScript: The Complete '0 to Hero' Beginner Course

33. Control Flow: The if...else Structure

The if...else statement allows you to execute one block of code if the condition is true, and a different block of code if the condition is false.

Syntax

javascript if (condition) { // Executes if condition is TRUE } else { // Executes if condition is FALSE }

Example

We want to determine if a user has access based on whether they are logged in.

javascript let isAuthenticated = false;

if (isAuthenticated === true) { console.log('Access Granted: Showing dashboard.'); } else { console.log('Access Denied: Redirecting to login page.'); }

// Output: Access Denied: Redirecting to login page.

Single Statement Optimization

If the block contains only one statement, the curly braces are optional, but using them is generally considered safer and better practice.

javascript let isDay = true;

if (isDay) console.log('Good morning'); // Single statement, braces omitted else console.log('Good evening');