Expressions and Side Effects in JavaScript

Expressions can also have side effects (such as variable assignment) in addition to producing a value.

Indeed, expressions in JavaScript can have side effects. This means that evaluating the expression can change the state of the program in some way, such as modifying a variable, altering data, or outputting information. Here are a few examples of expressions with side effects:

  1. Assignment expressions: When you assign a value to a variable, this is a side effect because it modifies the state of the variable.
1
2
let x = 5; // The state of 'x' is changed.
x = 10;    // The state of 'x' is changed again.
  1. Increment/Decrement expressions: Using the increment (++) or decrement (--) operators can modify the value of a variable. These expressions return a value and also have a side effect of updating the variable.
1
2
3
let count = 10;
count++;    // Now count is 11, so the state of 'count' has been changed.
count--;    // Now count is 10 again, another change in state.
  1. Function calls: A function call can have side effects if the function changes the state of something. This could include changing the value of a variable, modifying an object, or outputting information.
1
2
3
4
let arr = [1, 2, 3];
arr.push(4);   // The state of 'arr' is changed. Now it is [1, 2, 3, 4]

console.log("Hello, world!");  // Outputting information is a side effect
  1. Property assignments: Assigning a value to a property of an object is a side effect because it changes the state of the object.
1
2
let obj = {a: 1};
obj.a = 2;   // The state of 'obj' is changed.

Even though these expressions have side effects, they also produce values. The assignment x = 10 has the value 10, the increment count++ has the value 11, the function call arr.push(4) returns the new length of the array (4), and the property assignment obj.a = 2 has the value 2. This is consistent with the general rule that every expression in JavaScript produces a value.