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 “=”.

OperatorUsageSame AsDescription
=x = yx = yAssign a value to a variable
+=x += yx = x + yAdd a value to a variable
-=x -= yx = x – ySubtract a value from a variable
*=x *= yx = x * yMultiplie a variable
/=x /= yx = x / yDivide a variable
%=x %= yx = x % yAssign 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";