Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The if statement is a fundamental control flow structure in JavaScript that executes a specific statement or block of code only when its associated condition evaluates to a truthy value. It forces the JavaScript engine to evaluate an expression in a boolean context, dictating the execution path of the program based on that evaluation.

Syntax

if (condition) {
  // Statement(s) executed if condition is truthy
} else if (alternativeCondition) {
  // Statement(s) executed if alternativeCondition is truthy
} else {
  // Statement(s) executed if all preceding conditions are falsy
}

Evaluation Mechanics

Implicit Boolean Coercion JavaScript does not require the condition expression to be a strict boolean type (true or false). The engine applies the internal ToBoolean abstract operation to the evaluated expression. Falsy Values If the condition resolves to any of the following strictly defined falsy values, the if block is bypassed:
  • false
  • 0 and -0
  • 0n (BigInt zero)
  • "", '', `` (empty strings)
  • null
  • undefined
  • NaN (Not a Number)
  • document.all (a legacy web-specific host object explicitly defined as falsy by the ECMAScript specification via the [[IsHTMLDDA]] internal slot)
Truthy Values Any value that is not in the falsy list is considered truthy. This includes structures that developers sometimes mistakenly assume are falsy, such as empty objects ({}), empty arrays ([]), and strings containing only whitespace (" ").

Execution Behavior

Branching and Short-Circuiting In an if...else if...else chain, the JavaScript engine evaluates conditions sequentially from top to bottom. The moment a condition evaluates to a truthy value, its corresponding block is executed. All subsequent else if or else blocks are entirely skipped; their conditions are not evaluated. Block vs. Single Statement The curly braces {} define a block statement. If the execution body consists of only a single statement, the braces are syntactically optional:
if (true) console.log("executed");
However, omitting braces is generally discouraged in modern JavaScript style guides, as it can lead to structural ambiguity and errors during refactoring.

Lexical Scoping

The block statement {} associated with an if clause creates a new lexical scope.
  • Variables declared with let and const inside the block are strictly bound to that block and cannot be accessed from the outer scope.
  • Variables declared with the legacy var keyword ignore block scope entirely; they are hoisted and bound to the enclosing function or global scope.
if (true) {
  const blockScoped = "isolated";
  var functionScoped = "accessible";
}

// console.log(blockScoped); // ReferenceError
// console.log(functionScoped); // "accessible"
Master JavaScript with Deep Grasping Methodology!Learn More