Why can't i use the = instead of == operator in this function?

Tell us what’s happening:

Hey all, just a little confused as to why i can’t use = instead == in this function.

Also - why is “Eagle” strokes <= par - 2? Shouldn’t it just be == par -2? if it was less than -2 - say par - 3 it would be a Hole-in-one?

Thanks!
Matt

Your code so far


var 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 if (strokes == par - 1){return names [2]}
else if (strokes == par){return names [3]}
else if (strokes == par + 1){return names [4]}
else if (strokes == par + 2){return names [5]}
else if (strokes >= par + 3){return names [6]}



// Only change code above this line
}

console.log(golfScore(5, 9));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36.

Challenge: Golf Code

Link to the challenge:

JavaScript has 3 uses of =

  1. Single = : assign the value on the right to the variable on the left
  2. Double == : loose comparison of the two sides, do they evaluate to the same result
  3. Triple === : strict comparison of the two sides, are they the same thing and same type

In this case, you can’t use = for comparison. You’d always get a true on the first if since myVar = myVal is truthy so long as the assignment is successful.

Jeremy there got it right. But here’s an example for all that he used:

  1. Single = you can only use for assigning variables
const variable = value;
let variable2 = value
variable = value;
  1. Double == is used for loose comparison, it doesn’t have to be the same type of variable and such
let variable1 = true;
let variable2 = 1;

if (variable1 == variable2) {
//code will run
}

since true in computers means 1 that means it will run the code

  1. Triple === is used for strict comparison.
let variable1 = 1;
let variable2 = "1";
if (variable1 === variable2 ) {
//this code will not run
}

the code won’t run because variable 1 is an integer while variable2 is a string

1 Like

Since others have already answered the = vs == vs === question, I’ll answer your second question:

Your question assumes that the highest par value is 4. If that were true, then yes, par-3 would be a hole in one. If it’s a hole-in-one, the function terminates with the first condition of the if statement , so the second and subsequent lines will not run.