Answers for "Don’t Use If-Else and Switch in JavaScript, Use Object Literals"

0

Don’t Use If-Else and Switch in JavaScript, Use Object Literals

const getValue = (value) => ({
  [value == 1]: 'Value is 1',
  [value > 1]: 'Value is greater than 1',
  [value < 1]: 'Value is less than 1',
})[true]

console.log(getValue(2));
console.log(getValue(-1)); 
console.log(getValue(-1+2)); // expect 'Value is 1'
Posted by: Guest on April-20-2021
0

Don’t Use If-Else and Switch in JavaScript, Use Object Literals

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

var drink = getDrink('coke');
// The drink I chose was Coke
console.log(drink);
Posted by: Guest on April-20-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language