Statement vs Expression in JavaScript

Understanding the difference between statements and expressions is essential to grasp the flow and logic of JavaScript code.


1. Expression

An expression produces a value. It can be used wherever a value is expected.

  • Examples:

    // Arithmetic expression
    2 + 2
    
    // String expression
    "Hello" + " World"
    
    // Function call expression
    Math.max(5, 10)
    
    // Boolean expression
    5 > 3
    

    Expressions can be part of a larger expression:

    let sum = (2 + 3) * 5; // Expression `2 + 3` is evaluated to 5
    


2. Statement

A statement performs an action. It is a complete unit of execution but does not return a value directly.

  • Examples:
    // Variable declaration (statement)
    let x;
    
    // Conditional statement
    if (x > 0) {
      console.log("x is positive");
    }
    
    // Loop statement
    for (let i = 0; i < 5; i++) {
      console.log(i);
    }
    

Statements typically control the flow of the program (e.g., loops, conditionals) and do not produce values directly.


Key Differences

Aspect Expression Statement
Produces a Value Yes No
Used in Assignments Can be assigned to variables Cannot be directly assigned
Purpose Evaluates to produce a result Executes a piece of logic or action
Example 2 + 3, "Hello" + "World" if, for, let x = 5


Mixing Statements and Expressions

In JavaScript, expressions can be part of statements, but statements cannot be part of expressions. For instance:

// Expression within a statement
let result = (2 + 3) * 5; // The expression `(2 + 3)` evaluates to 5

// Statement
if (result > 10) {
  console.log("The result is greater than 10"); // Statement inside if block
}


Conclusion

  • Use expressions when you need a value or a computation.
  • Use statements for actions like defining logic, controlling flow, or declaring variables.

Comments

Popular posts from this blog

Loading Windows in CLI mode

XHR/fetch Breakpoints Explained

What are Dump Files?