Skip to content

Latest commit

 

History

History
65 lines (52 loc) · 1.48 KB

change-switch-to-object.md

File metadata and controls

65 lines (52 loc) · 1.48 KB

How to Change a Switch Statement to an Object


In JavaScript, you can substitute the switch statement with an object.

The function below is a switch statement:

function whoPlaysWhere(val) {
let answer = "";

  switch (val) {
    case "Steph Curry":
      answer = "Golden State Warriors";
      break;
    case "LeBron James":
      answer = "Los Angeles Lakers";
      break;
    case "Kevin Durant":
      answer = "Brooklyn Nets"
      break;
    case "Giannis Antetokounmpo" :
      answer = "Milwaukee Bucks"
      break;
  }
  
  return answer;
}

The object below was formed using the switch statement above:

function whoPlaysWhere(val) {
let answer = "";

  const players = {
    "Steph Curry" : "Golden State Warriors",
    "LeBron James" : "Los Angeles Lakers",
    "Kevin Durant" : "Brooklyn Nets",
    "Giannis Antetokounmpo" : "Milwaukee Bucks",
  }
  
  answer = players[val];
  return answer;
}

The object below will return the same results as the one above:

function whoPlaysWhereObject(val) {
  return {
    "Steph Curry" : "Golden State Warriors",
    "LeBron James" : "Los Angeles Lakers",
    "Kevin Durant" : "Brooklyn Nets",
    "Giannis Antetokounmpo" : "Milwaukee Bucks",
  }[val];
}

example link - switch link - object