Golf Code nested if/elseif

I copied a bit of the activity I’m referencing for context. I accidentally used assignment instead of equality or strict equality at first.

My code was broken when I had originally put if(strokes = 1) as the very first condition to the nested statements. I would correctly get the “Hole-in-one!” string when strokes = 1 (which makes sense why that works since I would be assigning 1) but none of the other strings worked.

Why does if(strokes == 1) process the rest of the nested else/if statements but if(strokes = 1) escapes the function/not process the rest of the conditions?

Code:

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];
} else if (strokes <= par-2){
  return names[1];
}
.
.
. else {
  return names[6];
}

Thanks!

An if statement evaluates the expression inside the parentheses and then executes the following code if the expression is true. Setting a variable to a value like that is an expression and the return value is the value that was set on the variable. So this if statement was evaluating to 1 which is “truthy” in JS and thus it was always running.

1 Like

Technically the = is a function with a return value. You set strokes to one and then the entire expression evaluates to 1, which is truthy, so that if statement always executes.

1 Like

Okay, I get it now! This makes sense :smile:

Thanks all!

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