JavascriptFizzBuzz

From Traxel Wiki
Jump to navigation Jump to search

Use "else if"

const JSNum = Number(process.argv[2]); // reads in the value of the argument passed in after
// the name of the script and converts it to a number

const remainderJava = JSNum % 3; // calcs JSNum remainder when divided by 3
const remainderScript = JSNum % 5; // calcs JSNum remainder when divided bt 5

if (remainderJava === 0 && remainderScript === 0) { 
    console.log ('JavaScript');  // checks if JSNum is evenly divisible by both 3 and 5 and reports
} else if (remainderJava === 0) {
    console.log ('Java');  // checks if JSNum is evenly divisible only by 3 and not 5 and reports
} else if (remainderScript === 0) {
    console.log ('Script');  // checks if JSNum is evenly divisible only by 5 and not 3 and reports
} else {
    console.log (JSNum);  // checks if JSNum is not evenly divisible by either 3 or 5 and reports
}

Better Formatting of Nested Conditionals

If you do have to have nested conditionals, put the "if" on a new line, so you can align the closing curly brace with the if:

const JSNum = Number(process.argv[2]); // reads in the value of the argument passed in after
// the name of the script and converts it to a number

const remainderJava = JSNum % 3; // calcs JSNum remainder when divided by 3
const remainderScript = JSNum % 5; // calcs JSNum remainder when divided bt 5

if (remainderJava === 0 && remainderScript === 0) { 
    console.log ('JavaScript');  // checks if JSNum is evenly divisible by both 3 and 5 and reports
} else {
    if (remainderJava === 0) {
        console.log ('Java');  // checks if JSNum is evenly divisible only by 3 and not 5 and reports
    } else {
        if (remainderScript === 0) {
            console.log ('Script');  // checks if JSNum is evenly divisible only by 5 and not 3 and reports
        } else {
            console.log (JSNum);  // checks if JSNum is not evenly divisible by either 3 or 5 and reports
        }
    }
}