How to Use the Assignment Operator in JavaScript

02/10/2022
Contents
In this article, you will learn how to use the assignment operator in JavaScript.
What is the assignment operator?
The “=” (equal) symbol used when assigning a value to a variable is called an assignment operator.
For example, use it as follows.
var variable = value;
There are several types of assignment operators other than “=”.
Operator | Usage | Same As | Description |
---|---|---|---|
= | x = y | x = y | Assign a value to a variable |
+= | x += y | x = x + y | Add a value to a variable |
-= | x -= y | x = x – y | Subtract a value from a variable |
*= | x *= y | x = x * y | Multiplie a variable |
/= | x /= y | x = x / y | Divide a variable |
%= | x %= y | x = x % y | Assign a remainder to a variable |
Examples
The assignment operator can be used in various ways, but this time I will introduce four examples.
1.Initialization when defining variables
let count = 0;
let array = [];
2.Store another value in a predefined variable
count = 1;
3.Use the additive assignment operator as an abbreviation for numerical calculations
let count = 0;
if(){
count += 2;
}
4.Assign values to HTML parts
document.getElementById("id").value = "Hello World";