Using objects and arrays for storage and access

The code you write can be greatly improved by taking a minute to think about how we store something, not just what we store. Objects and arrays are two storage vessels that, used wisely, keep your code DRY and easy to read.

Let’s go back to this example from earlier in the course:

function checkCountryCode(code){
    if (code === 'ZA') console.log('South Africa')
    else if (code === 'UAE') console.log('The United Arab Emirates')
    else if (code === 'CN') console.log('China')
    else if (code === 'GH') console.log('Ghana')
    else if (code === 'IN') console.log('India')
    else if (code === 'PH') console.log('Philippines')
    else console.log('Unknown')
}

The thing I want you to notice here is the use of a string identifier. Each of these strings is used to identify a country. Whenever string identifiers are used in combination with conditional flow, alarm bells should ring 🔔🚨.

A senior-level pattern to avoid messy conditionals

We have the perfect storage structure that entirely removes the need for such complicated flow:

const countryNames = {
    ZA: 'South Africa',
    UAE: 'The United Arab Emirates',
    CN: 'China',
    GH: 'Ghana',
    IN: 'India',
    PH: 'Philippines',
};

function getCountryName(code) {
    return countryNames[code] ?? 'Unknown';
}

This is called the dictionary or lookup pattern. Instead of building complicated conditional flow, or looping through arrays, we simply ask the captain if there is a genie with that name on the ship.

It’s faster, and much easier to change: adding a country is one new line of data, not another branch of logic. The values don’t have to be strings either - a lookup object can hold functions, one for each kind of action. You will see that pattern in many libraries.