Several condition for FOR loop with logical AND(&&) in JavaScript - javascript

need your help. I need to check whether it was entered number between 1-7 or not and check whether is empty line or not. What's wrong in my code below:
let number = parseInt(prompt('Choose number from 1 to 7'));
for ( ; (!number) && (number > 7); ) {
number = parseInt(prompt('Choose from 1 to 7'));
}
mood(number);
variable number goes for some function

You need an OR not an AND logical statement.
I would also use a do/while loop for clarity instead of for:
let number
do {
number = parseInt(prompt('Choose number from 1 to 7'));
} while (!number || number < 1 || number > 7);

The logic for which you want to check this requires you to use OR instead of AND operator.
When you are using AND, it is never evaluating 'truthy'.
Try ( ; (!number) || (number > 7); )instead of ( ; (!number) && (number > 7); )

You should change your (&&) to (||)

Related

Recognize anything which is not a number and return null [duplicate]

This question already has answers here:
How can I check if a string is a valid number?
(50 answers)
Closed 5 months ago.
I was writing a factorial function and I wanted to add a logic that returns null if the user puts anything into the argument instead of numbers like symbols (##!) or letters (s,z).
how can I recognize them and immediately stop my program and return null?
I know some ways but they will make my code really ugly and hard to read and long.
function factorial(n){
let num = Number(n);
// make num - 1 each time and push it into the list
let miniaturizedNum = [];
for (num; num > 0; num--){
miniaturizedNum.push(num);
}
// Multiply the finalresult with the numbers in the list
// and finalresault is 1 because zero multiplied by anything becomes zero
let finalResault = 1;
for (let i = 0; i < miniaturizedNum.length; i++){
finalResault *= miniaturizedNum[i];
}
return finalResault;
}
Assuming
you want to accept both numbers and strings representing a number (and convert them to number)
you want do avoid non integers and negative numbers since you're calcolating the factorial
if( typeof( n ) !== 'string' &&
( typeof( n ) !== 'number' || Number.isNaN( n ) ) &&
( '' + n ).match(/^[0-9]+$/) === null ) {
return null;
}
Check the datatype of the variable by using the typeof function, and if its not a number, then throw a TypeError

Javascript: confusion on using Logical NOT ! Operator

I am slightly confused on the logical NOT operator in Javascript (!). From my understanding, this is mainly used to "inverse" a boolean value. For example, if an expected output of a boolean is true, putting this in front would turn it to false, and vice versa.
In my below code, I created a function allowing user to input a lower and upper integer, and the function would generate a random number between this range. If, however, the user inputs a string instead of an integer, it will prompt the user to enter an integer instead.
I am using isNaN to check if user's input is an integer, and using logical NOT operator in front of it to inverse the result.
In my if condition, if I check isNaN for lower && isNaN for upper are both not a number, this program seems to work correctly. However, if I use ||, it doesn't work as expected, as shown in my code below.
Why is this so? By using OR operator, I am saying if either upper or lower is NaN, then prompt the user to enter a valid integer. Why is it a && and not a || when only one condition needs to be true?
const getNumber = function(lower, upper) {
if ( !isNaN(lower) || !isNaN(upper) ) {
const number = Math.floor(Math.random() * (upper - lower + 1)) + lower;
return number;
} else {
alert("Please enter a valid integer.");
}
};
// Call the function and pass it different values
console.log( getNumber('six',5) );
It's not the ! operator that's the problem, it's ||. if ( !isNaN(lower) || !isNaN(upper) ) { says (roughly) "if lower is a number or upper is a number". But you don't wan to say "or" there, because you want them both to be numbers.
So either use use && (and):
if ( !isNaN(lower) && !isNaN(upper) ) {
// −−−−−−−−−−−−−−−−^^
const number = Math.floor(Math.random() * (upper - lower + 1)) + lower;
return number;
} else {
alert("Please enter a valid integer.");
}
or reverse the content of your if and else blocks and use || without !:
if ( isNaN(lower) || isNaN(upper) ) {
alert("Please enter a valid integer.");
} else {
const number = Math.floor(Math.random() * (upper - lower + 1)) + lower;
return number;
}
Side note: You're using implicit string-to-number parsing in your code. I recommend doing it on purpose. My answer here goes into your various options for parsing numbers and their pros and cons.
By using OR, you are checking that at least one value should not be NaN.
let a = !isNaN(lower);
let b = !isNaN(upper);
a and b can be either true or false. When you use ||, you are telling that at least one of this values should be true. If you check Truth table, you will see that OR will be true for this combitations of a and b:
a == true, b == true
a == false, b == true
a == true, b == false
What you want is to check that a == true and b == true simultaneously - so you have to use AND (&&) which will evaluate to true if and only if a == true and b == true.

Why does this program not print anything in the page?

//This program calculates how many times a number is divisible by 2.
//This is the number and the amount of times its been split into 2.
let Num=64
let divisible=0
//This is the ternary operator, it basically asks a question.
Num % 2 === 0 ?
divisible=divisible++ : document.write(divisible);
Num/=2;
Num % 2 === 0 ?
divisible=divisible++ : document.write(divisible);
num/=2
Num % 2 === 0 ?
divisible=divisible++ : document.write(divisible);
//Once the statement evaluates to false it writes the amount of times the number has been divided
by 2 into the document.
You could try it with a loop.
let num=64;
let divisible=0;
while(num % 2 === 0) {
num /= 2;
divisible++;
}
console.log(divisible);
document.write(divisible);
There are several issues with this code. Some of the comments have pointed out the looping concerns. However, one that stands out that won't be addressed with a loop is your misuse of the post-fix increment operator, ++. This operator returns the value and then increments the value, so divisible = divisible++ will result in divisible remaining unchanged. Based on your intent, all you need to do is divisible++.
Try the following:
while(true){
if(Num % 2 === 0){
divisible++;
Num /=2;
}
else{
document.write(divisible);
break;
}
}
Here as per example given for 64 and no looping is provided , it will never go to
document.write(divisible) statement in 3 step provided above . That's why nothing getting printed .
Moreover , divisible=divisible++ doesn't make any sense . Here , since it is postfix operartor , first value will be assigned then it will be incremented so value of divisible will be 0 only .
Num % 2 === 0 ?divisible++ : document.write(divisible);
And , as per my understanding document.write accepts string parameter but here divisible is of number type .

Checking remainder in Javascript

I am super new at Javascript. I'm trying to write a script that logs numbers in order, and then at the end tells me if the final number is even or odd.
What I have is:
var i = 0;
do {
i++;
console.log(i)
}
while (i <= 9);
if(i % 2 = 1) {
console.log("odd")
}
else {
console.log("even")
}
Before I added the if/else, it worked. Now I keep getting the error: invalid left-hand side in assignment
What am I doing wrong? And to really display my ignorance, what is the left-hand side in the assignment?
Thanks!
Firstly, you will want to use the double equal (==) or the triple equal (===), when checking your remainder, since the single equal (=) is used to assign values to variables.
Difference between == and ===:
=== is more strict than == since === checks the value AND type whereas the == only checks the values.
Example:
if(1 == '1') // true
if(1 === '1') //false : their types are different.
Secondly, you will likely want to wrap your if statement inside of your do-while loop to get an output of even or odd after logging each number.
Here is the final result:
var i = 0;
do {
i++;
console.log(i);
if(i % 2 === 1) {
console.log("odd");
} else {
console.log("even");
}
} while (i <= 9);
When it says invalid left-hand side, it means that you are trying to assign a value to something on the left side. You have used -
if(i % 2 = 1)
However, = is an assignment operator, which basically assigns a value to a variable on the left. What you need is == which is a comparison operator since you are trying to compare two values.
This should be your code -
if(i % 2 == 1)
Instead of = it should be == in the if condition.
you need to change if condition from if(i % 2 = 1)
to
if(i % 2 ==1)
if(i % 2 == 1) {
console.log("odd")
}else {
console.log("even")
}
Because == is for equality comparison while = is for assigning of value.
So the problem in you code is , you are using an assignment operator "=" in your if condition, instead use "==" (comparision operator).
You can find more information on comparision operators in Javascript here :
https://www.w3schools.com/js/js_comparisons.asp

javascript testing if a value is a number AND a number greater than 0

I have an object property that may or may not contain a number and that number may or may not be equal to 0. For the moment, I have this:
var TheVar = parseInt(SomeObject.SomeVar, 10);
if (!TheVar > 0) {
TheVar = "-";
}
I want TheVar to be either a positive number or "-". I'm just wondering if my conditional statement is going to cover every case?
Thanks for your suggestions.
No. You are missing parentheses.
if( !(TheVar > 0))
NaN > 0 returns false, so the if condition will go through.

Categories

Resources