JavaScript Assignment
JavaScript assignments are used to store values in variables. They are one of the most basic and important concepts in JavaScript. An assignment takes a value, expression, or result and places it into a variable, property, or other valid destination.
For example:
let name = "Dibya";
Here, "Dibya" is assigned to the variable name. The = symbol is called the assignment operator.
Assignment is not limited to simply putting a value into a variable. JavaScript provides several assignment operators that can assign values, perform calculations, and then update variables in a shorter way.
What Is Assignment in JavaScript?
An assignment means giving a value to a variable or changing the value already stored in it.
let age = 25;
The statement tells JavaScript to create a variable called age and assign the value 25 to it.
The general form is:
variable = value;
For example:
let city = "Bhubaneswar";
let score = 100;
let price = 49.99;
Each statement assigns a value to a variable.
Assignment can also use an expression:
let total = 10 + 20;
JavaScript evaluates 10 + 20 first and then assigns the result, 30, to total.
The Basic Assignment Operator =
The most commonly used assignment operator is =.
let x = 10;
It assigns 10 to x.
A common beginner mistake is confusing assignment with comparison.
let x = 10;
Here, = assigns a value.
By contrast:
x == 10
checks whether x is loosely equal to 10, while:
x === 10
checks whether x is strictly equal to 10 and has the same type.
Therefore:
x = 10;
and:
x === 10;
have completely different purposes.
Assignment with let
The let keyword is commonly used when a variable’s value may change.
let count = 1;
count = 2;
count = 3;
The value of count changes as new assignments are made.
Another example:
let message = "Hello";
message = "Welcome";
After the second assignment, message contains "Welcome".
Assignment with const
A variable declared with const must be assigned a value when it is declared.
const country = "India";
You cannot later assign another value to the same const binding:
const country = "India";
country = "Japan"; // TypeError
This makes const useful when the binding should not be reassigned.
However, const does not automatically make an object or array immutable.
const user = {
name: "Dibya"
};
user.name = "Alex";
This is allowed because the object itself has not been replaced. The property inside the object was changed.
But this is not allowed:
user = {};
The variable binding cannot be reassigned.
Assignment with var
JavaScript also has the older var keyword.
var age = 20;
age = 21;
The variable can be reassigned.
Modern JavaScript generally prefers let and const because they provide clearer scoping rules and help avoid several common problems associated with var.
Reassigning a Variable
A variable declared using let can receive a new value.
let language = "JavaScript";
language = "Python";
The first value is replaced by the second value.
You can also change the type of a variable because JavaScript is dynamically typed:
let value = 10;
value = "Hello";
value = true;
This is valid JavaScript, although changing types unnecessarily can make code harder to understand.
Assigning Expressions
The right side of an assignment can contain an expression.
let result = 5 * 10;
JavaScript calculates 5 * 10 and assigns 50 to result.
Expressions can include variables:
let a = 10;
let b = 20;
let sum = a + b;
Here, sum receives 30.
You can also use function calls:
let length = "JavaScript".length;
Or:
let value = Math.max(10, 25);
The returned result is assigned to the variable.
Multiple Assignments
JavaScript allows several variables to be assigned in one statement.
let a = 10, b = 20, c = 30;
Each variable receives its corresponding value.
You can also use chained assignment:
let a, b, c;
a = b = c = 10;
The value 10 is assigned to c, then to b, and finally to a.
Although this is valid, separate assignments are often easier to read:
let a = 10;
let b = 10;
let c = 10;
Addition Assignment +=
The += operator adds a value to an existing variable and assigns the result back to that variable.
let score = 10;
score += 5;
Now score is 15.
This is equivalent to:
score = score + 5;
It is often useful for counters and totals.
let total = 100;
total += 25;
The final value is 125.
With strings, += can also concatenate text:
let message = "Hello";
message += " World";
The result is:
Hello World
Subtraction Assignment -=
The -= operator subtracts a value from a variable.
let balance = 100;
balance -= 30;
The final value is 70.
It is equivalent to:
balance = balance - 30;
Multiplication Assignment *=
The *= operator multiplies the current value by another value.
let price = 50;
price *= 2;
The result is 100.
It is equivalent to:
price = price * 2;
Division Assignment /=
The /= operator divides a variable by another value.
let amount = 100;
amount /= 4;
The final value is 25.
It is equivalent to:
amount = amount / 4;
Remainder Assignment %=
The %= operator calculates the remainder and assigns it back to the variable.
let number = 17;
number %= 5;
The result is 2.
It is equivalent to:
number = number % 5;
This can be useful when working with repeating patterns, cycles, and even-or-odd calculations.
Exponentiation Assignment **=
The **= operator raises a number to a power and assigns the result.
let number = 2;
number **= 3;
The result is 8.
It is equivalent to:
number = number ** 3;
Bitwise Assignment Operators
JavaScript also provides assignment operators based on bitwise operations.
These include:
&=
|=
^=
<<=
>>=
>>>=
They are mainly used when working with binary data, flags, low-level algorithms, or specialized programming tasks.
Bitwise AND Assignment &=
let value = 6;
value &= 3;
This performs a bitwise AND operation and assigns the result back to value.
Bitwise OR Assignment |=
let value = 6;
value |= 3;
This performs a bitwise OR operation.
Bitwise XOR Assignment ^=
let value = 6;
value ^= 3;
This performs a bitwise XOR operation.
Left Shift Assignment <<=
let value = 4;
value <<= 1;
This shifts the binary representation to the left.
Signed Right Shift Assignment >>=
let value = 8;
value >>= 1;
This performs a signed right shift.
Unsigned Right Shift Assignment >>>=
let value = 8;
value >>>= 1;
This performs an unsigned right shift.
These operators are less common in everyday web development but are important in specialized JavaScript applications.
Logical AND Assignment &&=
JavaScript provides logical assignment operators that combine logical operations with assignment.
The &&= operator assigns the right-hand value only when the current value is truthy.
let username = "Dibya";
username &&= "Admin";
The result is "Admin" because the original value was truthy.
A useful example is:
let user = {
name: "Dibya"
};
user.name &&= user.name.trim();
Conceptually, this is related to:
user.name = user.name && user.name.trim();
but the logical assignment form can avoid unnecessary evaluation of the right-hand expression.
Logical OR Assignment ||=
The ||= operator assigns a new value when the current value is falsy.
let name = "";
name ||= "Guest";
The result is:
Guest
This is commonly useful for default values.
For example:
let username = inputName || "Guest";
can often be expressed as:
username ||= "Guest";
when updating an existing variable.
Remember that || considers values such as 0, "", false, null, and undefined to be falsy.
Nullish Coalescing Assignment ??=
The ??= operator assigns a value only when the existing value is null or undefined.
let username = null;
username ??= "Guest";
Now username contains "Guest".
The important difference between ||= and ??= is that ??= does not treat every falsy value as missing.
For example:
let score = 0;
score ??= 100;
The value remains 0.
But:
let score = 0;
score ||= 100;
changes the value to 100 because 0 is falsy.
This distinction is extremely useful when 0, false, or an empty string is a valid value.
Assignment Operators at a Glance
| Operator | Meaning | Example |
|---|---|---|
= | Assign | x = 5 |
+= | Add and assign | x += 5 |
-= | Subtract and assign | x -= 5 |
*= | Multiply and assign | x *= 5 |
/= | Divide and assign | x /= 5 |
%= | Remainder and assign | x %= 5 |
**= | Exponentiate and assign | x **= 2 |
&= | Bitwise AND and assign | x &= 2 |
| ` | =` | Bitwise OR and assign |
^= | Bitwise XOR and assign | x ^= 2 |
<<= | Left shift and assign | x <<= 2 |
>>= | Signed right shift and assign | x >>= 2 |
>>>= | Unsigned right shift and assign | x >>>= 2 |
&&= | Logical AND and assign | x &&= y |
| ` | =` | |
??= | Nullish coalescing and assign | x ??= y |
Assignment to Object Properties
Assignment is not limited to variables. You can assign values to object properties.
const person = {
name: "Dibya",
age: 25
};
person.age = 26;
The age property is updated.
You can also create a new property:
person.city = "Bhubaneswar";
Now the object contains a city property.
Assignment to Array Elements
Array elements can also be changed through assignment.
let colors = ["red", "green", "blue"];
colors[0] = "yellow";
The array becomes:
["yellow", "green", "blue"]
You can also assign a value to a new index:
colors[3] = "black";
JavaScript will expand the array to accommodate the new index.
Destructuring Assignment
Destructuring assignment allows values to be extracted from arrays or objects and assigned to variables.
For arrays:
let numbers = [10, 20, 30];
let [a, b, c] = numbers;
Now:
a = 10
b = 20
c = 30
For objects:
let person = {
name: "Dibya",
age: 25
};
let { name, age } = person;
The variables name and age receive the corresponding property values.
Destructuring makes it easier to work with structured data.
Swapping Variables with Assignment
Destructuring can also be used to swap two variables without creating a temporary variable.
let a = 10;
let b = 20;
[a, b] = [b, a];
After the assignment:
a = 20
b = 10
This is a convenient feature of modern JavaScript.
Assignment and Function Calls
A function call can be used on the right side of an assignment.
function getNumber() {
return 50;
}
let result = getNumber();
The function returns 50, which is then assigned to result.
You can also assign the result of built-in functions:
let maximum = Math.max(10, 50, 30);
The value of maximum is 50.
Assignment Expressions
An assignment itself is an expression in JavaScript. This means an assignment can produce a value.
let a;
let result = (a = 10);
Both a and result become 10.
This behavior can sometimes be useful, but overly complex assignment expressions can reduce readability.
For example:
let a, b;
a = b = 10;
is valid, but separate statements may be clearer in larger programs.
Assignment in Conditional Statements
Assignments can technically appear in conditions:
let value;
if ((value = 10)) {
console.log(value);
}
This works because the assignment expression evaluates to 10, which is truthy.
However, accidental assignment inside a condition is a common programming mistake.
For example:
if (value = 10) {
// ...
}
A programmer may have intended:
if (value === 10) {
// ...
}
Using strict comparison when you want to compare values helps avoid this kind of error.
Assignment in Loops
Assignment is frequently used in loops.
let i = 0;
while (i < 5) {
console.log(i);
i += 1;
}
Here, i += 1 updates the variable after each iteration.
A for loop commonly contains assignments as well:
for (let i = 0; i < 5; i += 1) {
console.log(i);
}
The i += 1 expression updates the loop counter.
Assignment and Data Types
JavaScript variables can hold different kinds of values.
let value = 10;
Later:
value = "Hello";
Later:
value = true;
JavaScript does not require you to declare a fixed type for a variable.
Common assignable values include:
let number = 100;
let text = "JavaScript";
let active = true;
let empty = null;
let missing;
let list = [1, 2, 3];
let user = { name: "Dibya" };
The value assigned to a variable determines its current runtime type.
Assignment and undefined
If a variable is declared without a value, its initial value is undefined.
let result;
You can later assign a value:
result = 100;
Similarly:
let value;
value ??= "Default";
Because value is undefined, the default value is assigned.
Assignment and null
null represents an intentional absence of a value.
let user = null;
You can later assign an actual object:
user = {
name: "Dibya"
};
The variable has been reassigned from null to an object.
Assignment with Strings
Strings can be assigned normally:
let title = "JavaScript";
You can also build strings using +=:
let message = "Hello";
message += " JavaScript";
The final value is:
Hello JavaScript
Template literals are often a cleaner choice for more complex strings:
let name = "Dibya";
let message = `Hello, ${name}`;
Assignment with Numbers
Numbers can be assigned directly or calculated.
let price = 500;
let quantity = 3;
let total = price * quantity;
The value of total is 1500.
Compound assignment is useful when updating numbers:
let total = 1000;
total += 500;
total -= 100;
The final value is 1400.
Assignment with Boolean Values
Boolean values are commonly used for application state.
let isLoggedIn = false;
isLoggedIn = true;
Logical assignment can also be useful when working with boolean-like values.
let enabled = true;
enabled &&= false;
Assignment and References
Objects and arrays are assigned by reference-like value semantics rather than by copying the complete object.
Consider:
let first = {
name: "Dibya"
};
let second = first;
second.name = "Alex";
Now:
console.log(first.name);
outputs:
Alex
Both variables refer to the same object.
This is different from assigning primitive values such as numbers and strings, which behave as independent values.
Assignment Does Not Mean Copying Everything
Consider:
let a = 10;
let b = a;
b = 20;
Changing b does not change a.
But with objects:
let a = { value: 10 };
let b = a;
b.value = 20;
a.value also becomes 20.
If you need a separate object, you can create a copy, for example:
let a = { value: 10 };
let b = { ...a };
b.value = 20;
Now a.value remains 10.
Assignment with Object Properties
You can use bracket notation for dynamic property names:
let person = {};
person["name"] = "Dibya";
You can also use a variable as the property name:
let property = "age";
person[property] = 25;
This is useful when property names are determined at runtime.
Assignment with Optional Chaining
Optional chaining is useful for safely reading nested properties, but it cannot be used as the target of a normal assignment.
This is invalid:
user?.name = "Dibya";
JavaScript does not allow optional chaining on the left-hand side of an assignment.
Instead, check the object first:
if (user) {
user.name = "Dibya";
}
Assignment and Strict Mode
JavaScript strict mode catches certain invalid assignments.
For example, assigning to an undeclared variable is an error in strict mode:
"use strict";
x = 10;
This causes a ReferenceError.
Without strict mode, older JavaScript behavior could create a global variable in some situations. Modern code should avoid relying on that behavior.
Assignment to Undeclared Variables
Avoid code like:
x = 10;
Instead, explicitly declare the variable:
let x = 10;
or:
const x = 10;
Explicit declarations make code easier to understand and prevent accidental global variables.
Assignment to const
A const binding cannot be reassigned.
const tax = 18;
tax = 20; // Error
But object properties can still change:
const product = {
price: 100
};
product.price = 120;
This is valid.
The important idea is that const protects the binding, not necessarily the contents of an object.
Assignment Operator Precedence
Assignment operators have relatively low precedence compared with many arithmetic operators.
For example:
let result = 10 + 20 * 2;
JavaScript evaluates the multiplication first, then the addition, and finally performs the assignment.
The result is:
50
Parentheses can make intended evaluation clearer:
let result = (10 + 20) * 2;
Now the result is 60.
When writing complex expressions, parentheses can improve readability and reduce mistakes.
Right-to-Left Behavior of Assignment
Assignment operators are generally evaluated from right to left.
For example:
let a, b, c;
a = b = c = 10;
The assignment effectively proceeds from the right side.
This is why chained assignments work, although using separate statements can often make the code easier to maintain.
Assignment and NaN
Assignments can store NaN, which means “Not-a-Number.”
let result = 10 / "Hello";
The result is:
NaN
You can test for it with:
Number.isNaN(result);
which returns true.
Assignment and Infinity
JavaScript also allows numeric results such as Infinity.
let result = 10 / 0;
The result is:
Infinity
This value can be assigned and used in later calculations.
Common Assignment Mistakes
Mistaking = for ===
Incorrect when you intend comparison:
if (x = 10) {
}
Usually, the intended code is:
if (x === 10) {
}
Reassigning a const
const name = "Dibya";
name = "Alex";
This produces an error.
Use let if reassignment is required.
Forgetting to declare variables
Avoid:
total = 100;
Prefer:
let total = 100;
Confusing ||= with ??=
These are not identical.
let value = 0;
value ||= 10;
changes value because 0 is falsy.
But:
let value = 0;
value ??= 10;
keeps value as 0 because 0 is neither null nor undefined.
Overusing compound assignment
Compound assignment is convenient, but code should remain readable.
Instead of making a complex expression difficult to understand:
total += calculateSomethingComplicated();
use a clearer structure when necessary.
Best Practices for JavaScript Assignment
Use const by default when a variable does not need reassignment.
const siteName = "NewNid";
Use let when the value needs to change.
let counter = 0;
counter += 1;
Avoid var in modern JavaScript unless you have a specific reason to use its older function-scoped behavior.
Choose meaningful variable names:
let totalPrice = 500;
is clearer than:
let x = 500;
Do not rely on confusing chained assignments when separate statements improve readability.
Be careful when assigning objects and arrays because multiple variables can refer to the same object.
Use ??= when null and undefined specifically represent missing values.
Use ||= only when all falsy values should trigger the default.
Prefer strict equality for comparisons:
value === expected;
rather than accidentally using assignment:
value = expected;
Practical Example
Consider a simple shopping cart:
let price = 500;
let quantity = 2;
let discount = 50;
let total = price * quantity;
total -= discount;
console.log(total);
The initial total is 1000. The discount is then subtracted, producing 950.
The same calculation could be written with regular assignment:
let total = price * quantity;
total = total - discount;
The compound assignment version is shorter:
total -= discount;
Another Practical Example
A page may need a default username:
let username = null;
username ??= "Guest";
console.log(username);
The final value is "Guest".
If an empty string should also be treated as missing, logical OR assignment may be more appropriate:
let username = "";
username ||= "Guest";
The final value is "Guest".
Why JavaScript Assignment Matters
Assignment is at the heart of JavaScript programming. Applications constantly store and update information.
A web application may assign:
- User names
- Form values
- Prices
- Counters
- Login states
- API responses
- Configuration settings
- Object properties
- Array elements
- Calculated results
- Temporary values
Without assignment, variables would have no practical way to receive or update data.
Assignment also works closely with variables, operators, expressions, functions, arrays, objects, loops, conditions, and destructuring. Understanding it therefore makes many other JavaScript concepts easier to learn.
Final Summary
JavaScript assignment means storing or updating a value in a variable, object property, array element, or another valid assignment target.
The basic assignment operator is:
=
JavaScript also provides compound assignment operators such as:
+=
-=
*=
/=
%=
**=
It provides logical assignment operators:
&&=
||=
??=
and bitwise assignment operators such as:
&=
|=
^=
<<=
>>=
>>>=
Assignment can work with simple values, expressions, function results, objects, arrays, and destructuring.
The most important distinction to remember is that = assigns a value, while == and === compare values. In modern JavaScript, prefer const for bindings that do not need reassignment and let for bindings that do.
A strong understanding of JavaScript assignment provides a foundation for writing cleaner, safer, and more maintainable JavaScript code.