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:
| Parameter | Type | Description |
|---|---|---|
| condition | Expression | Evaluated for truthiness. |
| ternary ? : | Inline Operator | condition ? exprIfTrue : exprIfFalse |
Ready-to-Run Code Example
Executable in CompilraRun 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
JavaScript Switch Statement and Multiple Case Handling
Use the switch statement to perform different actions based on different conditions.
JavaScript For Loops, for...of, and for...in Iteration
Master classical for loops, for...of for iterable items, and for...in for object properties.
JavaScript Break and Continue Statements in Loops
Interrupt or skip loop iterations with break and continue statements.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.