Basic JavaScript - Golf Code -> Why Else statements?

Tell us what’s happening:
Hi. My code is working and passes the test. Can someone clarify to me why then you would even declare else statements, if it runs like this anyways?

Your code so far

const names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];

function golfScore(par, strokes) {
  // Only change code below this line
if (strokes == 1) {
  return names[0];
if (strokes - par <= -2) {
  return names[1];
if (strokes - par == -1) {
  return names[2];
if (strokes == par) {
  return names[3];
if (strokes == par + 1) {
  return names[4];
if (strokes == par + 2) {
  return names[5];
  return names[6];
  // Only change code above this line

golfScore(5, 4);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: Basic JavaScript - Golf Code

Link to the challenge:

I spoilered your solution for anyone who hasn’t yet tackled this problem.

A main reason for if ... else syntax is for clarity. It’s easier to read and understand blocks of code quickly, if they are presented in a simple, logical manner.
When I see an if ... else block, I can read it immediately as a block rather than a sequence of if statements.

Also, though it’s not applicable here, if you have two if statements in succession where you’re not returning out of the function (e.g. incrementing/decrementing a variable), using an else if obviates the possibility that both if statements could be true and have unwanted side-effects in your code (i.e. the else if code will only be triggered if the previous condition is false and the else if condition is true).

For this challenge, I’d prefer to use a switch statement, as I find that more elegant than an if ... else block, but that’s just my preference.

So, there’s nothing technically wrong with your code, but it’s good practice to try to present code in the most elegant and legible format possible (performance issues notwithstanding).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.