Replacing if statements with object lookups

This article shows how object lookups can sometimes be used as a more maintainable alternative to if statements.

Selecting a matching value

The code below determines the travel speed based on the mode of transport that was selected.

var speed;
if (modeOfTransport === "car") {
    speed = 40;
} else if (modeOfTransport === "train") {
    speed = 80;
} else if (modeOfTransport === "plane") {
    speed = 500;

This example is essentially mapping one value to another value. It uses an if statement to determine the corresponding speed value for each transport type.

An object lookup provides a cleaner way to write the code above:

var transportSpeeds = {
    car: 40,
    train: 80,
    plane: 500

var speed = transportSpeeds[modeOfTransport];

For example, if my modeOfTransport is "train" this code will retrieve the value of transportSpeeds["train"]. So in this case the travel speed is 80 (mph, or whatever the unit is).

Using an object like this allows us to separate the speed data from the logic that matches the mode of transport to the travel speed.

Determining multiple values

If you set more than one value in each if statement you can create an object for each mode of transport:

var dataByModeOfTransport = {
    car: {
        image: "/img/car.jpg",
        speed: 40
    train: {
        image: "/img/train.png",
        speed: 80
    plane: {
        speed: 500,
        image: "/img/aircraft.png"

var transportData = dataByModeOfTransport[modeOfTransport];
var speed = transportData.speed;
var image = transportData.image;

This lets you map the transport type to an object containing data about it.

Matching functions

In JavaScript, you can also set functions as values inside an object. This means your lookup can return a different function based on the mode of transport:

var setupMethods = {
    car: function(){
    train: function(){
    plane: function(){

var setupMethod = setupMethods[modeOfTransport];

After retrieving the correct setup method we can call it to run the initialization code that's specific to each mode of transport.

This allows us to customize the setup for each transport type in a clean way that doesn't use a long if statement.

Get an email with a new articles once a week.