# Alternate to a switch case - Javascript

I have a piece of code which works but I am looking for an optimal solution, if one exists. I have a column value and the value can only range from 2 to 10 including 2 and 10. The base value inside a switch is 18. Whenever the column value increases by 1, I need to decrease the value inside the switch by 0.5.

This is what I have:

const columns = 10;

const getVal = (columns) => {
switch (columns) {
case 2:
return 18
case 3:
return 17.5
case 4:
return 17
case 5:
return 16.5
case 6:
return 16
case 7:
return 15.5
case 8:
return 15
case 9:
return 14.5
case 10:
return 14
}
}

console.log(getVal(5))

Is there a better solution to achieve the same thing? Thanks.

• This isn't a programming question, this is a math question. And an easy one as well. You don't need a switch, you need a method that executes the proper calculation and returns the result. Dec 17, 2020 at 16:02

I would suggest simply converting the logic to a mathematical formula, rather than handling each case separately. This results in much shorter code, and clarifies that there is in fact a mathematical relationship between the input and output.

const getVal = (columns) => {
return 18 - ((columns - 2) * 0.5);
}

for (let x = 2; x <= 10; x++) {
console.log(x, getVal(x))
}

I would also highly recommend renaming the function getVal. I can't suggest a better name because I don't know what the reason for the function is, but I would think about what the output represents, and rename the function to indicate that.

You could make the getVal function much shorter - it can be done in one line. However, whether or not this is advisable depends (in my opinion) on the experience levels of the developers who will read this code (i.e. yourself and any collaborators). If the shorter form is likely to confuse people then I would suggest sticking to something written out more fully, but if the syntax is familiar then it does save a bit of space.

const getVal = columns => 18 - (columns - 2) * 0.5;

for (let x = 2; x <= 10; x++) {
console.log(x, getVal(x))
}

• Your solution has changed the behavior of the function, returning a number for all inputs rather than just for the ints 2-10. A rather dangerous thing to do. Never change a function's behavior in an unknown/unfamiliar environment. Dec 18, 2020 at 3:00
• That is true. I did consider mentioning checking the input values are integers in the expected range, but I decided to interpret "the value can only range from 2 - 10" as meaning the OP has full control over the input and has already validated it. You are right that this is modified behaviour though, thanks for pointing that out.
– Tim
Dec 18, 2020 at 7:26