DEV Community

loading...

Discussion on: Finally Understanding JavaScript

Collapse
patricktingen profile image
Patrick Tingen

I think you can do better with the birthday song. Why not use a loop to 4 instead of 2 and use an IF-THEN-ELSE construction to print the different line on the count of 3.....
Apart from that: happy coding :)

Collapse
lynnecodes profile image
Lynne Author

Nice! I didn’t think of that! Thanks so much for pointing that out. That’s great advice and I’ll keep that in mind for improvement. 👍🏼

Collapse
ericgeek profile image
EricGeek

If-then-else? How about picking up another technique, the ternary operator?

while (i < 4) {
let message = (i ==3) ? "Happy Birthday dear " + name + "," : "Happy Birthday to you.
";
document.write(message);
i = i + 1;
}

Which isn't the end of ways to refactor this. You could get rid of the temporary variable by having the ternary inside the document.write(), and you could change the while loop to a for loop. There's almost never only one way to do something when it comes to programming.

Collapse
lynnecodes profile image
Lynne Author

This is great! Thanks for building on this code and showing me another way to write it! I'm learning so much.