How to increment a conditional statement based on the five times table? - javascript

I am trying to achieve the following within my conditional statement:
if (changeCount == 5 || changeCount == 10 || changeCount == 15 || changeCount == 20) {
Do Something
}
I want to let the conditional statement pass if the value of the changeCount is any number in the five times table.
At the moment I have used the || however this is no good because I need it to be infinite.
I feel like a noob asking this question but any help would be great.
Thanks

Use the remainder operator (also known as the mod operator)
if (changeCount % 5 === 0) {
// do something
}
It works by dividing arg1 by arg2, and returning the remainder. If the remainder is 0, then it divides evenly.
If you wanted to limit the range of changeCount and still ensure that it is divisible by 5, you could do something like this:
if (changeCount >= lowerBound
&& changeCount <= upperBound
&& changeCount % 5 === 0) {

Related

A program that prompts the user to enter a number, and then checks whether the number is divisible by 7 and 11, or either 7 or 11

//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.
(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.
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}`);

Checking divisibility and converting digits into text

Check the divisibility of 2, 3, and both 2 and 3
Divisible by 2 - print x
Divisible by 3 - print y
Divisible by 2 and 3 - print xy
let num = prompt('1-1000');
if (num %2 == 0 )
{
console.log("X")
}
if (num %3 == 0 )
{
console.log("Y")
}
if (num %3 == 0 && num %2 ==0)
{
console.log("XY")
}
Example:
Input: 6
Output:
X
Y
XY
How to make it not print X, Y but XY?
What needs to be done so that several digits to be checked after the decimal point can be entered and then converted to the appropriate letters?
There are a couple of ways you could do this.
One way would be to use a ternary operator to output the values X and/or Y. This will have X logged only when divisible by 2, and Y only logged when divisible by 3. If it is divisible by both, both are shown but their conditions are independent of each other. And using template literals it is concatenated into 1 value.
let num = prompt('1-1000');
console.log(`${(num%2==0)?"X":""}${(num%3==0)?"Y":""}`);
Alternatively, you could use something like what was mentioned in the comments. If you convert the code to a function, you can move the final if statement to the top and use exit/return statements to return only 1 of the values (whichever applies).
const _Check = () => {
let num = prompt('1-1000');
if(num % 3 == 0 && num % 2 == 0) return "XY";
if(num % 2 == 0 ) return "X";
if(num % 3 == 0 ) return "Y";
return "";
}
console.log(_Check());
EDIT
In reponse to a comment by OP: checking for multiple numbers could be done by splitting the value input by the user and then looping through those values.
If the user will be inputting each number separated by a space, you can use the split() method with a space as the separator. And then use forEach() to loop through each number and apply the code/logic we have used earlier.
Example Using ternary operator and template literals:
let num = prompt('1-1000')
num.split(" ").forEach(n => {
console.log(`${(n%2==0)?"X":""}${(n%3==0)?"Y":""}`);
})
Example using a function and return statements:
let num = prompt('1-1000')
const _Check = n => {
if(n %3 == 0 && n %2 ==0) return "XY";
if(n %2 == 0 ) return "X";
if(n %3 == 0 ) return "Y";
return "";
}
num.split(" ").forEach(n => {
console.log(_Check(n));
})

Why do both these two solutions for printing all numbers divisible by 3 AND 5 between 5 and 50 work?

This was my solution to the problem:
var count = 5;
while (count <= 50) {
if ((count % 3 || count % 5) === 0) {
console.log(count);
}
count++;
}
This was my the instructors solution:
var count = 5;
while (count <= 50) {
if (count % 3 === 0 && count % 5 === 0) {
console.log(count);
}
count++;
}
Both of these solutions gave the proper answer, but I question why || worked in my problem, rather than &&, I tried both. && means both need to be true for it to properly run, right? So wouldn't that have been the proper use?
var count = 5;
while(count <= 50) {
console.log(`count = ${count} | (count % 3 || count % 5) = ${(count % 3 || count % 5)}`);
if((count % 3 || count % 5) === 0) {
console.log(count);
}
count++;
}
This happens because in all cases where count % 3 === 0 and count % 5 does not, the number takes precedence in the or (||) statement since it's "truthy".
eg.
count = 6, 0 || 1 // 1, since 0 is "falsy"
count = 8, 2 || 3 // 2
count = 15, 0 || 0 // 0
Therefore, it seems you stumbled on the correct solution.
It is a javascript peculiarity you encounter. If count % 3 is 0 it is considered "falsy" and the other calculation will be used. So if either modulus has a remains, that value is used in the final test against 0.
So while both works, your teachers code is more readable; thus better.
The following code
(count % 3 || count % 5) === 0
evaluates first the % operations and then the or to end with ===. If both modulo operations return 0, the or condition also evaluates as 0, that compared with 0 equals true and print the numbers. Otherwise, if any of the modulo values isn't 0, the or operation will result in these numbers, hence it won't be printed.
This is because Javascript evaluates numeric values as boolean being 0 False, and any other value True.
In your case it's a question of parenthesis
1st case of || with parenthesis like this ((count % 3 || count % 5) === 0) it like you say count has to be % by 3 and 5 so it's like &&
2nd case (count % 3 === 0 && count % 5 === 0) you've changed the parenthesis to regroup all
with && in the middle
so as i said it's question of parenthesis that makes both solution give the same result
Every value except 0 is evaluated as true. If there is a number divisible by 3 AND 5 both, then 0 || 0 is 0, which makes your if condition to run. If there is a number that is only divisible by 3 OR 5, lets say 10, then 10%3 is equal to 10 and 10%5 is equal 0. 10 || 0 will be evaluated as true (non-zero). Since non-zero value is not equal to 0 therefore if condition will not execute.
I am not sure but your instructors expression can be said as created from your expression by using Demorgans law.
The second solution is more useful than the first.
Because always "%" operator is computational, not logical

Javascript Function not defined error in code

I am new to Javascript and I don't understand why I am getting an error for this piece of code. Please help me understand what syntax I am got wrong.
var isEven = function(number){
if(number % 2 = 0){
return true;
} else {
return false;
};
};
isEven(5);
Change
if(number % 2 = 0)
to
if(number % 2 === 0)
because you want to test if the modulo 2 of number has no remainder. What you wrote was an illegal assignment operation.
(number % 2 = 0)
should be
(number % 2 == 0)
or
(number % 2 === 0)
One equal sign is assignment, the double equal sign is "equal to."
More info:
Triple equal sign matches type and value. (This is a good habit to get into using when possible.) Types are like "number", "object", "string" etc.
(number % 2 == 0) // true
(number % 2 == "0") // true
(number % 2 === 0) // true
(number % 2 === "0") // false
Otherwise, == might work with other things the computer considers zero, maybe null, maybe empty quotes, or maybe not, there's so many caveats in JS typing, === prevents most of those type headaches.
You are using the assignment operator instead of the equality operator in your if statement. This causes a JavaScript error because the value on the lefthand side of the operator isn't a variable, it's an expression.
What you want to do is check for equality. To do this, change = to === in your if statement.
if (number % 2 === 0)

What is the best way to check >= and <= in Javascript?

I have a number.
I then have an if statement that I want to go like this:
if (5 <= variable <= 10)
So if the number is between 5 and 10, the statement should be true.
What's the best way to go about this?
Thanks.
it is
if (5 <= variable && variable <= 10)
if ((variable >= 5) && (variable <= 10)) works.
If you do this frequently, consider defining a bounds function:
function inBounds(value, min, max){
return ((value >= min) && (value <= max));
}
Actually, if ( 5>= variable >= 10 ) means if(false)
if you means variable between 5, 10 it should be 5 <= variable <=10, and in javascript, the best convention is const value at left, which is from c language if (v=1), if (1=v) problem. so the best is:
if (5 <= variable && 10 >= variable) {
It is my understanding that at the first conditional false, it stops the checking and moves to the next statement.
Given that, you should examine the most often false condition and put it first.
if ((variable >= 5) && (variable <= 10))
if it is more likely to be less than 4 or
if ((variable <= 10) && (variable >= 5))
if the failure of 10 or greater is more likely to occur.

Categories

Resources