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 simple assignment operator (=) assigns a value to a variable, property, or destructuring pattern. It modifies the memory binding of the Left-Hand Side (LHS) expression to point to the evaluated Right-Hand Side (RHS) value.
LeftHandSideExpression = AssignmentExpression

Evaluation Mechanics

According to the ECMAScript specification, when the JavaScript engine encounters the = operator, it performs the following sequence of operations:
  1. LHS Resolution: The engine first evaluates the LeftHandSideExpression to resolve its memory reference (an l-value).
  2. RHS Evaluation: The engine then fully evaluates the AssignmentExpression on the right side to produce a value.
  3. Value Binding: The evaluated RHS value is stored in the memory location dictated by the LHS reference.
  4. Return: The operation resolves to the assigned RHS value, making the assignment itself an expression.

Return Value

Because the assignment operation returns the evaluated RHS value, it can be embedded within larger expressions.
let y;
// The expression (y = 5) evaluates to 5, which is then added to 10
let x = 10 + (y = 5); 

Associativity

The = operator has right-to-left associativity. When multiple assignment operators appear in the same expression, the JavaScript engine resolves the assignments from right to left.
let a, b, c;
// Evaluated as: a = (b = (c = 5))
a = b = c = 5;
In this sequence, the reference for a, b, and c are resolved left-to-right. Then, c = 5 is executed, returning 5. That return value is assigned to b, which returns 5, which is finally assigned to a.

Left-Hand Side Constraints

The LeftHandSideExpression must resolve to a valid reference (a variable, object property, or array element) or a valid destructuring assignment pattern.
  • Invalid Reference: If the LHS is an unresolvable reference or a primitive value, a SyntaxError or ReferenceError is thrown.
// SyntaxError: Invalid left-hand side in assignment
5 = x; 
  • Constant Reassignment: If the LHS is a reference bound via the const declaration, the engine throws a TypeError at runtime, as the binding is immutable.
const PI = 3.14;
// TypeError: Assignment to constant variable.
PI = 3.14159; 
  • Destructuring: The LHS can be a complex pattern, allowing the = operator to unpack values from arrays or properties from objects into distinct variables.
let a, b, x, y;

[a, b] = [1, 2];
({x, y} = {x: 10, y: 20});
Master JavaScript with Deep Grasping Methodology!Learn More