What's the difference between && and || in JavaScript? [duplicate] - javascript

This question already has answers here:
Logical operators in JavaScript — how do you use them?
(2 answers)
Closed 5 years ago.
Here's a perfect illustration I saw.
&&
if (num > 5 && num < 10) {
return "Yes";
}
return "No";
||
if (num > 10 || num < 5) {
return "No";
}
return "Yes";
What's the difference between these two?

They are AND (&&) and OR (||) operators.
In your first example the response will only be "Yes" if num is greater than 5 AND less than 10, so any value for num between 5 and 10 (exclusively) will return "Yes".
In your second example "No" will be returned if num is greater than 10 OR less then 5, so any value between 5 and 10 (inclusively) will return "Yes".

To make the expression
num > 5 && num < 10
negative,
!(num > 5 && num < 10)
you need to apply De Morgan's law
!(num > 5) || !(num < 10)
and reverse the condition inside of the parens
num <= 5 || num >= 10
In your question you have the expression with logical Or ||
num > 10 || num < 5
which is, despite the order, obviously not the same as the above expression. The result of comparing values is not the same.

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

Prime Number Function in Javascript ...multiple statements

So I'm tasked with making program that can tell whether a number is prime or not. I want to solve this problem using a multiple if-statement. The one that I came up with is awkward. So i just want some feedback on how to make it better.:
function primenumber(num) {
if (num / num === 1 && num % 2 !== = 0 || num % 3 !== = 0 | num % 5 !== = 0 | num % 7 !== = 0) {
return true;
} else {
return false
}
}
I figured these numbers are the lowest common denominators. So a number is prime if these numbers don't divide evenly into it. Any feedback is greatly appreciated. Keep in mind that I am new to Javascript.
I figured it out:
If((num === 1) || (num === 2) || (num === 3) || (num === 5) || (num === 7))
{ return true;
}
If((num%2===0) || (num%3===0) || (num%5===0) || (num%7===0)){
return false;}
}
return true;
}
It may not be the most sophisticated coding but it's mine and it works perfectly.. at least according to coderbyte

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