Yes, there often are alternatives to a long chain of if/else statements. They may be better or worse depending on the situation.
In your particular case, you have way more if statements than you need. You only need one if statement per possible response. Read the challenge instructions again carefully. For example, if strokes is 1 it’s a Hole-in-one regardless of what par is.
You can use the names array instead of hardcoding the strings to be returned.
Yeah, it’s ugly, but it may be the clearest. Of course, whenever you have a chain of equalities, that is screaming for a switch statement. But there are a few edge cases in there too:
if (strokes===1)
return "Hole-in-one!";
if (strokes<=par-2)
return "Eagle!";
switch (strokes-par) {
case -1:
return "Birdie";
case 0:
return "Par";
case 1:
return "Bogey";
case 2:
return "Double Bogey";
default:
return "Go Home!";
}
One single if statement for each return value, not only one in your code. Look at the description of the challenge again to identify what the condition should be for each return value.
Right now your solution passes the tests, but doesn’t actually work correctly. For example, golfScore(4, 1) should return "Hole-in-one!", but it would return "Change Me".
this is not final answer. I have added more code and completed that challenge.
this is just a small part of code ,i wanted to know alternative for this multiple if else.
I haven’t done all the new lessons yet. I also haven’t done the projects because I’m not very motivated to. I’m a professional developer and I’m part of FCC primarily to help teach new aspiring developers like yourself.
There’s a few of us knocking around on the forum. You’re always welcome to ask questions. You’ll probably also find that many questions that you may have specifically for professional developers have been brought up before. The forum has a really good search functionality.
Yes .I also work for a company but only html-css part I do there because I don’t have much expertise in JS.
So completing fcc certification to get good at JS and TS .like arrow function, ajax, callback ,closure, promise, observables…I want to be master at that. So practicing here.
I now regret posting completed answers. I skimmed the OP question and didn’t examine the code closely enough - I assumed the OP had a completed answer and wanted to know about alternatives. I hope the OP doesn’t copy mine but builds his own.
But yes, a chain of if/else statements is a valid solution, but Ariel is right that your logic was off.
No, I didn’t mean that as a criticism of you, just that I didn’t read closely enough and I shouldn’t have given you alternative answers until you’d gotten and answer of your own. We’re all learning here.