0
\$\begingroup\$

I'm trying to create an if-else statement that pops up a modal with output in the body, and if there is no input detected then an alert pops up.

    //fizzbuzz
$("#btnfb").click(function () {
var numfiz = $("#fizz").val();
var numbuz = $("#buzz").val();
var outputarray = [];
for (var loop = 1; loop <= 100; loop++) {
if (loop % numfiz === 0 & loop % numbuz === 0) {
outputarray.push("<span class='boldItalicPurple'>Fizzbuzz</span>");
}
else if (loop % numfiz === 0) {
outputarray.push("<span class='boldItalicGreen'>Fizz</span>");
}
else if (loop % numbuz === 0) {
outputarray.push("<span class='boldItalicOrane'>Buzz</span>");
}
else {
outputarray.push(loop);
}
$("fzbzout").html(outputarray.join(", "));
$('#myModel5').modal('show');
});
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

FizzBuzz is a popular interview question so following good programming practices are a good idea.

One key part of working with people on a larger project is readable code. Your code is very difficult to read because it is all aligned at the left side. There are also no spaces between things which can be valuable for grouping blocks of code. Something like this would be much more likely to impress your potential employer:

// Bhaskar's fizzbuzz in JavaScript/jquery

$("#btnfb").click(function () {
    var numfiz = $("#fizz").val();
    var numbuz = $("#buzz").val();
    var outputarray = [];

    for (var loop = 1; loop <= 100; loop++) {
        if (loop % numfiz === 0 & loop % numbuz === 0) {
            outputarray.push("<span class='boldItalicPurple'>Fizzbuzz</span>");
        } else if (loop % numfiz === 0) {
            outputarray.push("<span class='boldItalicGreen'>Fizz</span>");
        } else if (loop % numbuz === 0) {
            outputarray.push("<span class='boldItalicOrane'>Buzz</span>");
        } else {
            outputarray.push(loop);
        }
    $("fzbzout").html(outputarray.join(", "));
    $('#myModel5').modal('show');
});

By formatting the code this way it became immediately apparent that the for loop didn't have a closing }. Even if you have to do this on a whiteboard I would still stick with formatting things like this. For more detailed rules than "indent inside squigglies" check out Google's JavaScript style guide.

A second key part of working with others on software projects is providing useful comments. I skip this on whiteboard exercises because I'm probably going to have to verbally walk someone through the code anyways. But skipping it when I've got a keyboard available to me seems like a red flag that I would write code that cannot be maintained by anyone else.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.