Pages

[JS] Use object instead of swictch case

If you find yourself writing switch-case or long if-else clauses based on string comparision condition, consider switching it to use object instead. Object in Javascript can be dynamically updated which makes it very flexible. It works as a map so lookup is quick. For example, if you have some code like below.



function doSomething(message) {
  console.log(message);
}

function handleInput(input) {
  switch(input) {
    case VALUE1: 
      doSomething(MESSAGE1);
      break;
    case VALUE2:
      doSomething(MESSAGE2);
      break;
    default:
      throw new Error('not supportted input ' + input);
  }
}

You can always rewrite it as following.

 
function handleInput(input) {
  inputMessage = {
    VALUE1: MESSAGE1,
    VALUE2: MESSAGE2
  }
  if (!inputMessage[input]) {
    throw new Error('not supportted input ' + input);
  }
  doSomething(inputMessage[input]);
}

The code is now shorter but more readable and can be easily expanded in the future.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Node JS Online Training from India . or learn thru Javascript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Online Training

    ReplyDelete