Javascript Jumpstart - Statements & Expressions

The fundamental building blocks of the language

·

6 min read

Javascript Jumpstart - Statements & Expressions

What we'll cover

  • Expressions

  • Statements

  • When to convert an expression to a expression-statement

  • How to differentiate between expression and statement

Expression

  • An expression is any piece of code that evaluates to a value.

  • It can be as simple as a single value or more complex with operators and operands.

  • Examples of expressions:

    • 5 (evaluates to the value 5)

    • 2 + 3 (evaluates to the value 5)

    • x * 4 (evaluates to the value of x multiplied by 4)

  •         // Examples of expressions
            "abc" // "abc"
            10 // 10
            a + b // sum of "a" and "b"
    
            "Good" + "Evening" // "GoodEvening"
            a <= b || c !== d // "true" or "false"
            myFunction(c, d) // function result
    
            // assignment expression
            // it always produces a value
            // LVALUE and RVALUE
            // value 20 will be assigned to "a"
            a = 20 // 20
            let myObj = {
                a: true,
                b: null 
            };
    
            // assignment expression
            // this expression not only produces a value but also performs other action i.e reassigns
            value of property "a" in myObj
            myObj.a = 10 // 10
    
  • Each expression produces/evaluates to a value!

  • In assignment expression, there's always a LVALUE and RVALUE.*

  • LVALUE is an expression that refers to a location in memory, which is usually a variable name or could be the name field of a property in an object.

  • RVALUE is an expression that refers to a value.

  • Expression that produces a value and does an action, is called expression with side effects.

  • A function call is an expression, not a statement! It evaluates to a value or produces a value.

*A note on LVALUE and RVALUE

  1. Lvalue:

    • An lvalue refers to the left-hand side of an assignment operation.

    • It represents a storage location, such as a variable, to which a value can be assigned.

    • The lvalue is the target or destination of the assignment.

    • Examples of lvalues:

      • Variables: x, y, etc.

      • Object properties: object.property, object["property"], etc.

      • Array elements: array[index], etc.

  2. Rvalue:

    • An rvalue refers to the right-hand side of an assignment operation.

    • It represents the value that is assigned to the lvalue or used in an expression.

    • The rvalue can be a literal value, a variable, or an expression that resolves to a value.

    • Examples of rvalues:

      • Literal values: 5, 'hello', true, etc.

      • Variables: a, b, etc.

      • Expressions: x + y, 10 * (a + b), etc.

Statements

  • A statement is a complete line or block of code that performs an action or executes a sequence of operations.

  • Statements do not necessarily have value. Each statement produces an action!

  • They are typically used to control the flow of execution, perform repetitive tasks, or define functions and variables.

  •         // examples of statements
            let a;
            const b = 5;
            if(a > b) {
                console.log("A is larger");
            }
            for(let i = 0; i < 5; i++) {
                console.log(i);
            }
    
  • Usually ; semi-colon is added after statements, it is the most visible difference between statement and expression.

  • ; a semi-colon is not required after a block of statements.

  • Expressions can be turned into statements.

When to turn an expression into a statement

Expressions are typically used to produce values, while statements are used to perform actions or control the flow of the program. However, there are scenarios where you might need to turn an expression into a statement. Here are a few common situations:

  1. Function Invocation:

    • When you want to invoke a function that returns a value but you don't need the result, you can turn the function call into a statement by discarding the returned value using an expression statement or an assignment without using the result.
  2. Side Effects:

    • Sometimes, an expression has side effects (modifying state or performing actions) but doesn't necessarily produce a useful value. In such cases, you might convert the expression into a statement to explicitly indicate that the purpose is the side effect rather than the value.

    • Example:

        // Expression with side effect
        counter++;
      
        // Statement emphasizing the side effect
        counter++; // Incrementing the counter
      
  3. Object Creation:

    • When creating an object using the object literal syntax {}, it is treated as an expression that produces the created object. However, if you want to use object creation for its side effects, such as adding properties or invoking methods, you can convert it into a statement.

    • Example:

        // Expression
        const person = {
          name: 'John',
          age: 30,
          sayHello() {
            console.log('Hello!');
          }
        };
      
        // Statement emphasizing object creation
        const person = {}; // Object creation
        person.name = 'John'; // Adding properties
        person.age = 30;
        person.sayHello = function() { // Adding methods
          console.log('Hello!');
        };
      

It's important to note that turning an expression into a statement may be necessary in certain cases, but it should be used judiciously and with clear intent to improve code readability and maintainability.

How to differentiate between expression and statement

Expressions can be used as arguments in function calls.

statements and expressions are fundamental components of the language, serving different purposes and having distinct characteristics. Here are the key differences between statements and expressions:

  1. Purpose:

    • Statements: Statements are used to perform actions, control the flow of the program, and define functions, variables, and objects.

    • Expressions: Expressions are used to produce values. They can be as simple as a single value or more complex with operators and operands.

  2. Value:

    • Statements: Statements do not have a value or produce a value explicitly. They are executed for their side effects or to control the program's flow.

    • Expressions: Expressions evaluate to a value. They can be used to calculate a result, assign values, or pass values as arguments to functions.

  3. Syntax:

    • Statements: Statements are typically terminated with a semicolon (;). Examples of statements include if, for, while, function declarations, and variable assignments.

    • Expressions: Expressions are composed of operators, operands, and literals. They can be used within statements or standalone. Examples of expressions include arithmetic expressions (2 + 3), function calls, and variable references.

  4. Nesting:

    • Statements: Statements can contain other statements, creating a nested structure. Examples include nested if statements or loops within loops.

    • Expressions: Expressions can be embedded within statements or other expressions, but they cannot contain complete statements. For example, an expression can be used as part of a function argument or assigned to a variable.

  5. Execution:

    • Statements: Statements are executed sequentially unless control flow statements like if, for, or while change the order of execution.

    • Expressions: Expressions are evaluated to produce a value. They are executed as part of larger expressions or when assigned to variables.

Examples:

// Statement (variable declaration)
let x;

// Statement (if-else)
if (x > 0) {
  console.log("Positive");
} else {
  console.log("Non-positive");
}

// Expression (assignment)
x = 5;

// Expression (arithmetic)
const result = x * 2;

// Expression (function call)
console.log("Hello!");

// Statement (function declaration)
function greet(name) {
  console.log("Hello, " + name + "!");
}
  • Declaring variables with let, var or const is always a statement

In summary, statements are used for actions, control flow, and defining program structure, while expressions are used for producing values and calculations. Understanding the difference between statements and expressions is crucial for writing effective and meaningful JavaScript code.

That's it for this article, next we will dive into scopes and some inner workings of the javascript engine in Javascript Jumpstart - Scopes