Golf Code [why == works and = doesn't]

Tell us what’s happening:
I already cheated and looked up the answer. The code below is my incorrect code. I found out that by changing all the = to == the code works.

I’m not sure why though. Can someone please explain to me why == works but = doesn’t?

Thanks

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 {
    return names[6];
  }
  
  // Only change code above this line
}

// Change these values to test
golfScore(5, 4);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/golf-code

= is used to declare a variable
== is a logic operator that returns true or false if a = b

Example:

let a = 2
a = 5 //a now = 5

let a = 2
a==5 //returns false

1 Like

Just to add to what @lrothman says, = in JavaScript (and quite a few other languages, including all the most popular ones) is not the same as = in maths class. In JS assigns whatever is on the right hand side to the a variable on the left hand side:

Maths (1 + 1 is equal to 2):

1 + 1 = 2

JavaScript (1 + 1 is equal to 2):

1 + 1 == 2

And for variables, JavaScript

var y = (x) => // do something with x

The kinda equivalent in Maths

y = f(x) 

It’s only kinda though - in a programming language, you are saying “refer to this thing the name y so I can look it up in memory by just typing y rather than the code associated with it”, maths has no need for that so it isn’t as important at all.

1 Like

Thank you both for the answers. I understand the difference now. Much appreciated

Just to add a useful content to the post, also we have:
The Strict Equality Comparison Algorithm wich you can be used to evaluate if they have the same data type.

var a = 1;
var b = "1";

if(a === b) {
  document.writeln('true');
} else {
  document.writeln('false');
}

/**
    The result of that example compassion return false because
    they are not same using the same data type
**/

You can read more here