Home > Blockchain >  A program that prompts the user to enter a number, and then checks whether the number is divisible b
A program that prompts the user to enter a number, and then checks whether the number is divisible b

Time:12-13

//TASK 5 PART 1

//Request input from user
let x   = Number(prompt("Enter a number:"));

// using if...else if
if      (x % 7 === 0 && 
         x % 11 === 0) {
         console.log
        (x   " is divisible by 7 and 11");
}

else if (x % 7 === 0 || 
         x % 11 === 0) {
         console.log
        (x   " is divisible by either 7 or 11");
}

else                   {
         console.log
        (x   " is divisible by neither 7 or 11");
}

I am very new to JavaScript, and so I am here to ask for help on how to make my code more efficient, using less lines of code, perhaps a method better suited for this program, improve readability or if anybody spots any errors. I am always keen on receiving constructive criticism on where to improve.

Thank you all for your time.

CodePudding user response:

(x % 7 == 0) && (x % 11 == 0) ? "both" : (x % 7 == 0) || (x % 11 == 0) ? "either" : "neither"

Here I have used the nested ternary operator, to do the solution in one line.

The syntax is: let result = condition ? value1 : value2;

The condition is evaluated: if it’s truthy then value1 is returned, otherwise – value2.

To know more please refer to this article.

In my expierince first get comfortable with the basics first, then look to enhance your knowledge of advanced concept of Javascript.

CodePudding user response:

I'd write it like this.

const x = Number(prompt('Number:'));
const d7 = !(x % 7), d11 = !(x % 11);
const result = (d7 && d11) ? 'both 7 and 11' :
               (d7 || d11) ? 'either 7 or 11' :
                             'neither 7 nor 11';
console.log(`${x} is divisible by ${result}`);
  • Related