Golf code if and else if question

So this is the solution I arrived to:

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 "Hole-in-one!";
} else if (strokes <= par -2) {
return "Eagle";
} else if (strokes == par -1) {
return "Birdie";
} else if (strokes == par) {
return "Par";
} else if (strokes == par + 1) {
return "Bogey";
} else if (strokes == par + 2) {
return "Double Bogey";
} else {
return "Go Home!";
golfScore(5, 4);

It works but I am having trouble understanding how and why it works.
How does it know what par is if its not defined?
Is golfScore(5, 4); defining par, strokes?

Thanks in advance. I am trying to understand what I am doing instead of just powering through the content.

All parameters in a function’s definition are defined.

What defines par though if strokes == par + 2 what is it adding + 2 to? I hope I am not making this more confusing than it is. I just don’t get how it know what par + 2 is if par doesn’t = anything.

You might want to review the Passing Values to Functions with Arguments challenge. The parameters are placeholder variables which take on the values passed to them (arguments) when the function is called.

1 Like

Par is just the formal parameter name. When you define function golfScore(par, strokes), you are saying, “create a function called golfScore which accepts two variables, par and strokes.” When you call golfScore(5,4), you are passing a value of 5 to par and a value of 4 to strokes.

Also, your code will be a lot more readable if you use a switch statement, like so:

switch(strokes) {
	case 1:
		console.log("Hole in one");	
	case par - 2:
    case par + 2:
        console.log("Double Bogey");
1 Like

Dude, thanks. That is a great explanation, exactly what I was hoping to get.
The next lesson is on switch statements, I didn’t want to move on until I understood what I was doing.
Thanks so much!