Using object literals and map method instead of the old switch statement

Implementing ES6 features in our code it is best to use object literals instead of switch statements in our codes. In this article we will explain it with some examples.

First example: switch statement replaced

As an example take a look at this example which I want to explain:

function test(color) {
  // use switch case to find fruits in colour
  switch (color) {
    case 'red':
      return ['apple', 'strawberry'];
    case 'yellow':
      return ['banana', 'pineapple'];
    case 'purple':
      return ['grape', 'plum'];
    default:
      return [];
  }
}

//test results
test(null); // []
test('yellow'); // ['banana', 'pineapple']

Clearly we could see how switch statement works here. it finds or categorises fruits in colour. 

We know that switch statements, with their non standard syntax included, are difficult to read and contain extra “syntactical sugar (not good sugar)” that we really don’t want to be reading.

synthetical sugar

Object literals or map to help

Technically we could use object literals to replace the above switch statement like below:

function test(color) {
  // use object literals to find fruits in colour
  const fruitColor = {
    red: ['apple', 'strawberry'],
    yellow: ['banana', 'pineapple'],
    purple: ['grape', 'plum']
  };

  return fruitColor[color] || [];
}

We have created a JSON object that contains our colours as keys and fruits and the value we want to select from the object. We have a much cleaner code which is not error prone either. Aa an alternative we could use map and set to define the switch statement instead:

function test(color) {
  // use Map to find fruits in colour
  const fruitColor = new Map()
    .set('red', ['apple', 'strawberry'])
    .set('yellow', ['banana', 'pineapple'])
    .set('purple', ['grape', 'plum']);

  return fruitColor.get(color) || [];
}

As a result we have similar outcomes from the three of the code snippets above. But using ES6 features like object literals saves a lot of time and code. Also we will have a more maintainable code. 

Another example with object literals

Take a look at this similar example first with switch statement in the view:

let type = 'coke';
let drink;
switch(type) {
case 'coke':
  drink = 'Coke';
  break;
case 'pepsi':
  drink = 'Pepsi';
  break;
default:
  drink = 'Unknown drink!';
}
console.log(drink); // 'Coke'

Basically switch has lots of problems. from its procedural control flow to its non-standard-looking way it handles code blocks. AS the rest of JavaScript uses curly braces yet switch does not.

Using object literals it makes it easy to manage it all and have control over the code:

function getDrink (type) {
  let drinks = {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade',
    'default': 'Default item'
  };
  return 'The drink I chose was ' + (drinks[type] || drinks['default']);
}

const drink = getDrink('coke');
// The drink I chose was Coke
console.log(drink);

As a result we have more readable code which can be expanded to much more complex code with different conditions. The concept remains the same though. 

Thank you for reading.

© 2019
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.