Default Values with Destructuring
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — A Fallback When the Key Is Missing
Imagine you just caught a wild Zap whose `level` hasn't been recorded yet. If you destructure a property that doesn't exist on the object, JavaScript gives you `undefined`:
const zap = { name: "Zap" };
const { name, level } = zap;
console.log(name + " is level " + level);To avoid `undefined`, you can define a default value by writing `= value` right after the variable name. JavaScript will use this fallback whenever the property is missing:
const zap = { name: "Zap" };
const { name, level = 1 } = zap;
console.log(name + " is level " + level);Exercise 2 — Only undefined Triggers It
What happens if a property exists, or has a value like `0`, `""`, or `false`? A default value only triggers when the property is strictly `undefined` (missing). Any actual value in the object is kept:
const aquachu = { name: "Aquachu", hp: 0 };
const { hp = 100, shield = 50 } = aquachu;
console.log("HP: " + hp);
console.log("Shield: " + shield);Here `shield` is missing, so it falls back to `50`. On the other hand, `hp` is `0` — a real number — so it stays `0`. That's exactly what you want: a fainted Codémon shouldn't magically heal back to `100` HP!
Exercise 3 — Quiz: Default Used?
What does this code print?
const item = { name: "Rope" };
const { name, price = 10 } = item;
console.log(price);10undefined0Hint : Check whether the object actually has that key.
Exercise 4 — Give It a Default
Make `type` fall back to `"unknown"` when the property is missing.
Hint : A default looks like an assignment, and a piece of text needs its quotes.
Exercise 5 — Defaults in Arrays
Array destructuring accepts defaults too, for positions the array doesn't reach:
const scores = [10];
const [first = 0, second = 0] = scores;
console.log(first + " / " + second);Here the array has one element, so `second` falls back to 0 instead of being `undefined`. The sum below stays a real number:
const scores = [10];
const [first = 0, second = 0] = scores;
console.log(first + second);Exercise 6 — Quiz: Zero Stays
What does this code print?
const cdm = { level: 0 };
const { level = 5 } = cdm;
console.log(level);05undefinedHint : Is 0 the same thing as a missing property?
Exercise 7 — Defaults in Function Parameters
The most common use: a function receives an options object and fills in the blanks itself.
function createCodemon({ name, type = "normal", level = 1 }) {
console.log(name + " | " + type + " | Lv." + level);
}
createCodemon({ name: "Zap" });
createCodemon({ name: "Pyrochu", type: "fire", level: 8 });You can also rename and give a default at the same time: the key, then the new name, then the fallback.
const item = { name: "Potion" };
const { price: cost = 0 } = item;
console.log("Cost: " + cost);Exercise 8 — Options With Defaults
Give the function a default `power` of 10, so the first call prints 10 and the second prints 45.
Hint : The fallback sits right after the property name, written like an assignment.
Exercise 9 — Codémon Factory
Write a factory function that fills in whatever the caller leaves out.
Step 1: `describe({ name, type, level, hp })` destructures its parameter with these defaults: `type` is `"normal"`, `level` is `1`, `hp` is `20`. `name` has no default. Step 2: it returns `"name | type | Lv.X | Y HP"`. Step 3: print the result for three calls: only a name, a name with a type, and a fully described Codémon.
Expected output:
Zap | normal | Lv.1 | 20 HP
Pyrochu | fire | Lv.1 | 20 HP
Metachu | metal | Lv.15 | 90 HP// Write your function here
// Make the three calls here