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.

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.

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");	
		break;
	case par - 2:
		console.log("Eagle");
		break;
    case par + 2:
        console.log("Double Bogey");
        break;
    etc...
}
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!