🎉 New! Announcing our next generation AI code completions

Read here

How to Use the Assignment Operator in JavaScript

  • 2 min read
  • November 30, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

The Assignment operator is used to assign a value to a variable.

Assignment (=)

The assignment operator simply assigns the value of the right operand to the variable specified by the left operand.

let y = 5;

In the example above, let y is assigned the numeric value 5.

It is possible to assign any data type to a variable (e.g. String; Object; Function; etc.).

Assignments can be chained, allowing you to assign the value of the right operand to multiple variables in sequence.

The example code below demonstrates both the basic usage of the assignment operator, as well as the chaining functionality it enables:

let x = 5;
let y = 6;
let z = 7;
let a = 9;
x = y = z = a;
console.log(x, y, z, a);
// Expected output: 9 9 9 9

The example above defines four variables – x, y, z, and a – each with a different numeric value.

The fifth line of code assigns the value of the fourth variable (a, which contains the value 9) to the first three variables (x, y, and z). After this assignment, all four variables store the same numeric value – that of let a (9).

Other assignment operators

There are multiple types of assignment operators in JavaScript, in addition to the basic assignment operator detailed above:

Addition assignment (+=)

Subtraction assignment (-=)

Multiplication assignment (*=)

Division assignment (/=)

Remainder assignment (%=)

Exponentiation assignment (**=)

 

Related Articles

JavaScript – How to Use the substr Method

JavaScript – A Short Introduction to Loops

JavaScript – How to Use the onclick DOM Event

Related Posts

How to Use parseInt() in JavaScript

How to Use parseInt() in JavaScript

The parseInt function parses a string argument and returns an integer. In its most simple form, the function looks like this: const x = ‘8’; console.log(parseInt(x));

How to Use promises in JavaScript

How to Use promises in JavaScript

JavaScript is a synchronous language, yet sometimes asynchronous behavior is required. For example, you may need to use an asynchronous function while waiting for data to

How to use the for…of Statement in JavaScript

How to use the for…of Statement in JavaScript

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript. JavaScript offers many different types of loops, each