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
| Operator | Shorthand for | Example |
|---|---|---|
+= | x = x + y | total += price |
-= | x = x - y | count -= 1 |
*= / /= / %= | Same idea | price *= 1.1 |
**= | x = x ** y | n **= 2 |
&&= | Assign only if left is truthy | state &&= updated |
||= | Assign only if left is falsy | name ||= "anon" |
??= | Assign only if left is null/undefined | count ??= 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;
Two question marks.
Discussion
Loading…