Checking if something is an array
We cannot use the typeof operator in JavaScript to check if something is an array or not. Luckily, there is a helper function on the Array prototype for that.
Read fire tipThe 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
We cannot use the typeof operator in JavaScript to check if something is an array or not. Luckily, there is a helper function on the Array prototype for that.
Read fire tip