Destructuring in variable assignment
Destructuring lets us extract an object’s property into a variable of the same name in very little code.
Read full articleThe lookup table pattern can replace some long if
-else
branches and switch
statements. We can catch unknown keys we don’t have values for with hasOwnProperty
.
const getColorOf = (thing) => {
const map = {
clouds: "white",
grass: "green",
sky: "blue",
}
// throw an error if `thing` isn’t a key in the map
if (!map.hasOwnProperty(thing)) {
throw new Error(`Color not defined for: ${thing}`)
}
// if we get here, `thing` IS a key in the map
return map[thing]
}
getColorOf("grass") // ⇒ "green"
getColorOf("air") // ⇒ Color not defined for: air
getColorOf() // ⇒ Color not defined for: undefined
const getColorOf = (thing) => {
const map = {
clouds: "white",
grass: "green",
sky: "blue",
}
// throw an error if `thing` isn’t a key in the map
if (!map.hasOwnProperty(thing)) {
throw new Error(`Color not defined for: ${thing}`)
}
// if we get here, `thing` IS a key in the map
return map[thing]
}
getColorOf("grass") // ⇒ "green"
getColorOf("air") // ⇒ Color not defined for: air
getColorOf() // ⇒ Color not defined for: undefined
const getColorOf = (thing) => {
const map = {
clouds: "white",
grass: "green",
sky: "blue",
}
// throw an error if `thing` isn’t a key in the map
if (!map.hasOwnProperty(thing)) {
throw new Error(`Color not defined for: ${thing}`)
}
// if we get here, `thing` IS a key in the map
return map[thing]
}
getColorOf("grass") // ⇒ "green"
getColorOf("air") // ⇒ Color not defined for: air
getColorOf() // ⇒ Color not defined for: undefined
const getColorOf = (thing) => {
const map = {
clouds: "white",
grass: "green",
sky: "blue",
}
// throw an error if `thing` isn’t a key in the map
if (!map.hasOwnProperty(thing)) {
throw new Error(`Color not defined for: ${thing}`)
}
// if we get here, `thing` IS a key in the map
return map[thing]
}
getColorOf("grass") // ⇒ "green"
getColorOf("air") // ⇒ Color not defined for: air
getColorOf() // ⇒ Color not defined for: undefined
Destructuring lets us extract an object’s property into a variable of the same name in very little code.
Read full articleIf a switch-statement only serves to map a key to a value, we can use an object to do the same in fewer lines of code.
Read full articleIf you keep seeing stars in JavaScript, it’s probably someone trying to raise a number to the power of another number.
Read full articleAre you calling the same function many times with near-identical parameters? Hide that repetition in a higher-order function for more readability.
Read full articleTemplate literals allow us to put the values of variables, the results of calculations, and even return values of function calls into strings.
Read full articleInfinity is just a number, dude. Most calculations JavaScript lets us do with Infinity will still return Infinity. Some no longer return numbers.
Read full article