iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Assignment

The basic = operator assigns a value. Most arithmetic and logical operators have an "assignment" shorthand version that combines reading and writing.

Compound assignments

OperatorShorthand forExample
+=x = x + ytotal += price
-=x = x - ycount -= 1
*= / /= / %=Same ideaprice *= 1.1
**=x = x ** yn **= 2
&&=Assign only if left is truthystate &&= updated
||=Assign only if left is falsyname ||= "anon"
??=Assign only if left is null/undefinedcount ??= 0

Destructuring assignment

JS
// Swap
[a, b] = [b, a];

// Pull from objects
({ name, age } = user);   // parens required for object destructuring without `const/let`

// With defaults and rest
const { name = "anon", ...rest } = user;

Reference vs. value

JS
// Primitives are copied
let a = 1;
let b = a;
b = 2;
console.log(a);   // 1 — unchanged

// Objects/arrays are copied BY REFERENCE
const arr1 = [1, 2];
const arr2 = arr1;
arr2.push(3);
console.log(arr1);   // [1, 2, 3] — both names point at the same array
Tip: The new logical assignments (??=, ||=) are great for "set a default if missing": opts.timeout ??= 5000;

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Assignment!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Default options.timeout to 5000 only if it is currently null/undefined.

options.timeout = 5000;

Test yourself

Q1. Set count to 0 only if it is null/undefined with…
Q2. Objects assigned to a new variable are copied…
Q3. `x += y` is shorthand for…

Discussion

Loading…