Best practices snippets

Replacing switch statements or multiple if with Object literals

Bad way - switch :

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

 

Bad way - multiple If :

function getDrink (type) {
  if (type === 'coke') {
    type = 'Coke';
  } else if (type === 'pepsi') {
    type = 'Pepsi';
  } else if (type === 'mountain dew') {
    type = 'Mountain Dew';
  } else if (type === 'lemonade') {
    type = 'Lemonade';
  } else if (type === 'fanta') {
    type = 'Fanta';
  } else {
    // acts as our "default"
    type = 'Unknown drink!';
  }
  return 'You\'ve picked a ' + type;
}

 

Better way :

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

 

Null, Undefined, Empty Checks Shorthand

This  code :

let variable1 = "";
let variable2 = "12";
if (variable1 !== null && variable1 !== undefined && variable1 !== "") {
  variable2 = variable1;
}
console.log({ variable1, variable2 });

 

Can be replaced simply by :

let variable1 = "";
let variable2 = variable1 || "default";
console.log({ variable1, variable2 });

 

Clone an Object Using Spread

let user = {
  first: "chris",
  last: "burgin"
}
let userCopy = {...user}; // new object, not by ref

 

js best practices