Fizzbuzz Solution : Ultimate Javascript Course Part 1

What is the convention when it comes to mixing methods? I solved this fizzbuzz thing several ways… first with the ‘if’ method, then using the return (condition) ? input : method as follows:

const output = fizzBuzz(‘3’);
console.log(output);

function fizzBuzz(input) {
return ((input % 3 === 0 && input % 5 === 0) && Number.isInteger(input)) ? ‘FizzBuzz’ :
input % 3 === 0 && Number.isInteger(input) ? ‘Fizz’ :
input % 5 === 0 && Number.isInteger(input) ? ‘Buzz’ :
input && Number.isInteger(input) ? input : NaN;
}

However, I was unsatisfied with the number of times I added the check for integer. I also experimented with type of, but that was more code and using isNaN(input) worked everywhere except for when I entered true as the input. Finally, I settled on:

const output = fizzBuzz(‘3’);
console.log(output);

function fizzBuzz(input) {
if (typeof input !== ‘number’)
return NaN;

return input % 3 === 0 && input % 5 === 0 ? 'FizzBuzz' : 
input % 3 === 0 ? 'Fizz' : 
input % 5 === 0 ? 'Buzz' : 
input;
}

I had () wrapping each condition, but found the code evaluated the same without adding the parenthesis.

By using the if statement first then swapping to the return (condition) method, I use less code and it looks clean, but is it an acceptable practice / workplace convention?

Checking beforehand that you deal with a number is a good idea.

You should never nest the ternary operator. Use individual ifreturn … statements for each condition instead.

Although browsers understand if statements without parenthesis around the condition, ECMA requires them and developers expect them.

Thank you for the response, Sam. I had read the following articles prior and leave them here for your review.

https://rules.sonarsource.com/javascript/RSPEC-3358

I was under the impression that I was making them more readable similar to the “Compliant” example in the second link. I can see how in longer, more complex code, things could spiral out of control and be a pain to make sense out of, though. I’ll stick to the if, else, etc. method since it feels more like previous python experience anyway, but I do wonder if anything meaningful performance difference would occur from using one over the other.

I’d suggest you stick to common practices until you have a thorough understanding of the language and can make your own judgement based on your experience. Mosh has a good sense for clean coding so you can usually trust in his suggestions.

BTW: Shift-Alt-F in VS Code formats your code in the way Eric suggested so what he says doesn’t seem to be too odd although I’ve not seen it before and it looks somehat weird to me.

Thank you again, Sam! The goal is to be a productive and appreciated member of a team s I definitely do not want to drive anyone else crazy,