Today our coding challenge will let us figure out what is wrong with the code. within the function we have a switch statement that is not returning the correct value. Can you figure out what is wrong with this function?
const getPlanetName = (id)=>{
let results;
switch (id) {
case 1:
results = "Mercury"
case 2:
results = "Venus"
case 3:
results = "Earth"
case 4:
results = "Mars"
case 5:
results = "Jupiter"
case 6:
results = "Saturn"
case 7:
results = "Uranus"
case 8:
results = "Neptune"
}
return results
}
console.log(getPlanetName(1));
// output = Neptune
The function above will always return "Neptune" regardless of what input you put to the getPlanetName function. The reason why that is happening is because when you are using a switch statement, at the end of each "case", you should include a "break" statement. You will understand what I am talking about after seeing the solution to the above problem below.
const getPlanetName = (id)=>{
let results;
switch (id) {
case 1:
results = "Mercury"
break;
case 2:
results = "Venus"
break;
case 3:
results = "Earth"
break;
case 4:
results = "Mars"
break;
case 5:
results = "Jupiter"
break;
case 6:
results = "Saturn"
break;
case 7:
results = "Uranus"
break;
case 8:
results = "Neptune"
break;
}
return results
}
console.log(getPlanetName(7));
// output = Uranus
Now our function has been fixed. Thanks to the "break" keyword.