Start using Object Literals

Start using Object Literals

·

2 min read

Let's start this post with a brief discussion about what are switch case and object literals and then we'll move to why to use Object literals instead of Switch-case statements.


Intro

Switch-Case

(Src => FreeCodeCamp.com) A switch statement tests a value and can have many case statements which define various possible values. Statements are executed from the first matched case value until a break is encountered.

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Object Literal

A JavaScript object literal is a comma-isolated rundown of name-esteem sets wrapped in curly brackets.

let myObject ={
  myProperty : value,
  yourProperty : value,
  myMethod : function(){
    //CODE BLOCK
  },
  yourMethod : function(){
    // CODE BLOCK
  }
}

Why and when to use Object literals instead of Switch-case?

Performance for switch/if statements can be a concern when the number of cases becomes large. With a smaller number of cases, a switch is the faster option, while when the number of cases grows a single lookup in an object literal becomes the FASTER option.

EXAMPLE:

The code written below is error-prone when the "break" is missed and unreadable with the increase in the number of cases.

let search = "two", nmbr; 
switch(search) {
    case "one": 
     nmbr = 1; break; 
    case "two" :
     nmbr = 2; break; 
    case "three" : 
     nmbr = 3; break; 
     default: 
      console.log('case not found'); break;   
}; 
console.log(nmbr); //returns 2

Let's see how can we use this with Object.

Object literal Example:

This way, easily readable, with minimized error and optimized ES6 friendly conditional statements, can be achieved with Object-literals.

let search = "two"; 
let nmbr; 
var condition = {
    "one": ( () => { nmbr = 1; }),
    "two": ( () => { nmbr = 2; }),
    "three": ( () => { nmbr = 3; }),
}; 
const defaultFn = () => {
    console.log('case not found'); 
}; 
condition[search](); 
console.log(nmbr); // returns 2

NOTE: unlike switch-case "default" is not automatically executed.

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!