JavaScript:JavaScript If...Else, Ternary Operator, and Branching
JavaScript•Conditionals

JavaScript If...Else, Ternary Operator, and Branching

Learn conditional branching in JavaScript, nesting statements, and using ternary operators for concise expressions.

Syntax

if (condition) { // branch } else { // fallback }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
conditionExpressionEvaluated for truthiness.
ternary ? :Inline Operatorcondition ? exprIfTrue : exprIfFalse

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// Conditional Branching in JavaScript
const userRole = "editor";
let accessLevel;

if (userRole === "admin") {
  accessLevel = "Full Root Access";
} else if (userRole === "editor") {
  accessLevel = "Publish and Edit";
} else {
  accessLevel = "Read Only";
}

// Ternary expression
const canDelete = userRole === "admin" ? "YES" : "NO";

console.log("Role:", userRole);
console.log("Access:", accessLevel);
console.log("Can Delete Records:", canDelete);
Expected Output:
Role: editor
Access: Publish and Edit
Can Delete Records: NO

How It Works: Step-by-Step

  • Lines 5-11: Checks userRole strictly against permission tiers.
  • Line 14: Assigns canDelete conditionally with inline ternary syntax.

Key Concepts

  • JavaScript requires parentheses around the if (condition) expression.
  • Braces {} are recommended even for single-line blocks to avoid scoping bugs.
  • Ternary operators provide a readable shorthand for simple binary assignments.

Common Mistake: Using single = inside if statements instead of ===

if (x = 5) performs an assignment instead of a comparison, always evaluating as truthy.

❌ Incorrect
if (status = "active") { /* Bug: sets status and evaluates true! */ }
✅ Correct
if (status === "active") { /* Compares properly */ }

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler