Welcome ðŸŽ‰

logo

ReactLMS

Search
Light Mode
Contact Us

6 min to read

Contact us

No results for your search.
Sorry, an unexpected error occurred

Concept


Assignment is a fundamental and important part. It allows us to assign a value to a variable and manage data in a program.


Assigning a Value to a Variable


To assign a value to a variable in JavaScript, we use the assignment operator (=).

let name = "John"; // Gán giá trị chuỗi "John" cho biến name
let age = 25; // Gán giá trị số 25 cho biến age
let isStudent = true; // Gán giá trị boolean true cho biến isStudent






We can also assign the value of one variable to another variable as follows

let x = 10;
let y = x; // Gán giá trị của biến x cho biến y







Assignment Operators


In addition to the assignment operator (=), JavaScript also provides some other assignment operators to perform calculations and assign values at the same time.

Addition and assignment operator (+=): Used to add a value to the current value of a variable and assign the result to the variable.

let sum = 5;
sum += 3; // TÆ°Æ¡ng Ä‘Æ°Æ¡ng vá»›i sum = sum + 3






Subtraction and assignment operator (-=): Used to subtract a value from the current value of a variable and assign the result to the variable.

let difference = 10;
difference -= 4; // TÆ°Æ¡ng Ä‘Æ°Æ¡ng vá»›i difference = difference - 4






Multiplication and assignment operator (*=): Used to multiply a value with the current value of a variable and assign the result to the variable.

let product = 2;
product *= 6; // TÆ°Æ¡ng Ä‘Æ°Æ¡ng vá»›i product = product * 6






Division and assignment operator (/=): Used to divide the current value of a variable by a value and assign the result to the variable.

let quotient = 15;
quotient /= 3; // TÆ°Æ¡ng Ä‘Æ°Æ¡ng vá»›i quotient = quotient / 3






Modulus and assignment operator (%=): Used to get the remainder after dividing the current value of a variable by a value and assign the result to the variable.

let remainder = 17;
remainder %= 4; // TÆ°Æ¡ng Ä‘Æ°Æ¡ng vá»›i remainder = remainder % 4







Example with Code


Here are some examples of using assignment in JavaScript:

// Gán giá trị cho biến
let name = "John";
let age = 25;
let isStudent = true;

// Gán giá trị của biến cho biến khác
let x = 10;
let y = x;

// Sử dụng toán tử gán +=
let sum = 5;
sum += 3; // sum = 8

// Sử dụng toán tử gán -=
let difference = 10;
difference -= 4; // difference = 6

// Sử dụng toán tử gán *=
let product = 2;
product *= 6; // product = 12

// Sử dụng toán tử gán /=
let quotient = 15;
quotient /= 3; // quotient = 5

// Sử dụng toán tử gán %=
let remainder = 17;
remainder %= 4; // remainder = 1









Read more
On This Page