Appearance
Common Idioms
An idiom is a coding pattern that combines multiple language features to solve a common task. These patterns are widely used in JavaScript code because they're practical and easy to understand once you know the underlying concepts.
The following examples show how to combine features we've covered in previous sections (like spread/rest, destructuring, and array methods) to solve typical programming problems.
Create a Prepopulated Array
You can combine spread and map to create a numbered sequence or other patterned array:
js
// Create array [0, 10, 20, 30, 40]
const sequence = [...Array(5)].map((_, i) => i * 10);
// Create array ['A', 'B', 'C', 'D', 'E']
const letters = [...Array(5)].map((_, i) => String.fromCharCode(65 + i));Here's how this works:
Array(5)creates an array with 5 empty slots, but these slots are not actual values thatmapcan work with- The
[...]brackets with spread operator convert those empty slots into realundefinedvalues - Now
mapcan iterate over these values, using the indexito create the sequence
Props
When creating UI elements, we often pass in configuration options called "props". Destructuring with default values makes these props easy to handle. Here's how it works in imperative code:
js
// Imperative style with a class
class Button {
constructor({
label = "Click",
colour = "grey",
onClick = () => {}
} = {}) {
this.label = label;
this.colour = colour;
this.onClick = onClick;
}
draw(gc) {
gc.fillStyle = this.colour;
gc.fillText(this.label, 10, 20);
// rest of button drawing ...
}
}
const okButton = new Button({ label: "OK", colour: "blue" });
const cancelButton = new Button({ label: "Cancel" });Note the = {} default parameter means you can call either style without arguments, and the defaults will still work.
js
// uses all default values: a grey button labelled "Click"
const defaultButton = new Button();The same pattern will appear in declarative components with props, something like this:
js
// Declarative style with a function component
function Button({
label = "Click",
colour = "grey"
}) {
return `<button style="color: ${colour}">
${label}
</button>`;
}
// In a declarative framework, used like this:
<div>
<Button colour="blue" label="OK" />
<Button label="Cancel" />
</div>External Resources