while-loop doesnt stop after meeting the condition [duplicate] - javascript

This question already has answers here:
How do I test if a variable does not equal either of two values?
(8 answers)
Closed 10 months ago.
Just got started with Javascript and struggling with some pretty easy code:
"use strict";
function math () {
if (action == "+") {
return answer = firstNumber + secondNumber
}
else if (action == "-") {
return answer = firstNumber - secondNumber
}
else {
while(action != "+" || action != "-") {
action = prompt('Write an action (only "+" and "-" supported!!!):');
}
}
}
math(firstNumber, secondNumber,action);
alert(answer);
Even after condition in loop is false the loop still executes. Can you please explain what went wrong? Not just solution, please.

while(action != "+" || action != "-") will always evaluate to True
while(action != "+" && action != "-") is what you are looking for

The error here lies in the while loop conditional statement.
while(action != "+" || action != "-")
This statement will continue looping if action does not equal "+", or "-". If action is "+", we continue to loop because the action does not also equal "-". To fix this change your operator to an && instead of an || like this:
while(action != "+" && action != "-")

I guess, you just made an error when formulating your condition and most likely only want to continue looping until the entered action is neither of the two values. You therefore must use the and && and not the or || operator.
In other words: you want to continue until the value is not a plus sign AND not a minus sign.

First of all you don't need to write a while block there as when the compiler will check first two if statements that is if and else if (in order) and will not execute any of them this automatically means that action != "+" and also != "-" so you can directly write like this :
"use strict";
function math () {
if (action == "+") {
return answer = firstNumber + secondNumber
}
else if (action == "-") {
return answer = firstNumber - secondNumber
}
else {
action = prompt('Write an action (only "+" and "-" supported!!!):');
}
}
}
math(firstNumber, secondNumber,action);
alert(answer);
Also it is not stopping because it will run until the while condition is False but if the action is != "+" or "-" this means while condition will always be true because wrong action has been taken, so while loop will run infinitely... Try replacing while with "if statement" or the || operator in while loop with && operator

Related

Why is my JS function always returning true? [duplicate]

This question already has answers here:
Why doesn't my simple if-statement render false in javascript?
(2 answers)
Closed 6 years ago.
I'm trying to check if a string is blank, less than or equal to 9 digits, or up to 10 digits. But it always follows the else if (str.length <= 9).
if (str = ''){
console.log("The string cannot be blank");
} else if (str.length <= 9) {
console.log("The string must be at least 9 characters long");
} else if (str.length <= 10) {
console.log("The string is long enough.");
}
No matter what I put in, I always get The string must be at least 9 characters long. Why?
= is always assignment. Equality comparison is == (loose, coerces types to try to make a match) or === (no type coercion).
So you want
if (str === ''){
// -----^^^
not
// NOT THIS
if (str = ''){
// -----^
What happens when you do if (str = '') is that the assignment str = '' is done, and then the resulting value ('') is tested, effectively like this (if we ignore a couple of details):
str = '';
if (str) {
Since '' is a falsy value in JavaScript, that check will be false and it goes to the else if (str.length <= 9) step. Since at that point, str.length is 0, that's the path the code takes.

Why doesn't my equality comparison using = (a single equals) work correctly? [duplicate]

This question already has answers here:
Why doesn't my simple if-statement render false in javascript?
(2 answers)
Closed 6 years ago.
I'm trying to check if a string is blank, less than or equal to 9 digits, or up to 10 digits. But it always follows the else if (str.length <= 9).
if (str = ''){
console.log("The string cannot be blank");
} else if (str.length <= 9) {
console.log("The string must be at least 9 characters long");
} else if (str.length <= 10) {
console.log("The string is long enough.");
}
No matter what I put in, I always get The string must be at least 9 characters long. Why?
= is always assignment. Equality comparison is == (loose, coerces types to try to make a match) or === (no type coercion).
So you want
if (str === ''){
// -----^^^
not
// NOT THIS
if (str = ''){
// -----^
What happens when you do if (str = '') is that the assignment str = '' is done, and then the resulting value ('') is tested, effectively like this (if we ignore a couple of details):
str = '';
if (str) {
Since '' is a falsy value in JavaScript, that check will be false and it goes to the else if (str.length <= 9) step. Since at that point, str.length is 0, that's the path the code takes.

Why won't my if/else statement work? (JavaScript)

I'm trying to code a script to test whether a user-inputted number is prime or not. I'm coding several different primality tests, but one in particular is giving me a hard time.
function isPrimeSix() {
var numberPrimeSix = document.getElementById("primeSixInput").value;
var loopCount = 0;
for (var i = 1; i < Math.floor((numberPrimeSix / 6) + 1) + 1; i++)
{
if (numberPrimeSix === (6 * i) + 1)
{
//Irrelevant code here//
}
else if (numberPrimeSix === (6 * i) - 1)
{
//More irrelevant code//
}
else
{
loopCount++
}
};
if (numberPrimeSix === 2 || numberPrimeSix === 3 || numberPrimeSix === 5 || numberPrimeSix === 7)
{
alert(numberPrimeSix + " is prime.");
}
else if (prime === false || loopCount === Math.floor((numberPrimeSix / 6) + 1))
{
alert(numberPrimeSix + " is not prime.");
}
else if (prime === true)
{
alert(numberPrimeSix + " is prime.");
}
else
{
alert("Error");
};
}
Every time the for loop goes around, the embedded if statement will not evaluate, even if for that particular value of i one of the statements is true. Regardless of what number is assigned to numberPrimeSix, the script will always go to the else section of the loop, meaning that an alert will pop up telling me that the number is not prime (because the value of loopCount is equal to the value defined by the last if statement).
Can anyone tell me why this is? I hope this makes sense, and if the 'irrelevant code' is needed I'll provide it. Thanks!
A string will never be exactly equal (===) to a number. In JavaScript, if you use ==, the operands will be converted to be the same type before comparing. If you instead use ===, that step will be skipped and instead they will be tested for strict equality, meaning same type and value, not just same value.
You have two options. Replace === with ==, or, convert the value before the loop and continue using strict equal. It will be much faster to convert the value before the loop so that you're not converting it over and over with each iteration.
var numberPrimeSix = parseInt(document.getElementById("primeSixInput").value, 10);
more reading: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Can't make multiple if conditions in JavaScript?

I have absolutely no idea why this is not working. Makes no sense to me.
This returns a "syntax error: parse error":
if ($(this).attr("id") === 'search' || opening = true) return false;
For good measure, I also tried the following, which yielded the same result:
if (1 = 1 && 2 = 2) { return false; }
There are three different operators at play:
=: assignment
==: equality
===: strict equality
= actually modifies a variable, so you shouldn't use it inside if statements. That is, you should use ... || opening == true) instead of ... || opening = true).
In JavaScript = is used to assign values, while == and === are used to compare them.
When you put opening = true in your if statement, you aren't checking if opening is true, you are setting opening to true. Try using == instead.
For example,
var x = 5;
if (x == 10) {
alert("x is 10");
} else {
alert("x isn't 10");
}
will display "x isn't 10", while
var x = 5;
if (x = 10) {
alert("x is 10");
} else {
alert("x isn't 10");
}
will display "x is 10".
the first example should read:
if ($(this).attr("id") === 'search' || opening == true) return false;
and the second:
if (1 == 1 && 2 == 2) { return false; }
Note the double equals (==) sign for logic equals is not the same as the single equals (=) sign, that handles variable assignment.
You have an error in your condition
if ($(this).attr("id") === 'search' || opening = true) return false;
should be
if ($(this).attr("id") === 'search' || opening == true) return false;
the problem is with the equals sign
= is different to ==
the first one is the assignment operator. the second one is for comparison
When you test like this:
opening=true;
What you are really doing is setting opening to the value of true. Use == instead.
Finally, order of operations, even if correct, can get confusing. Put parenthesis around each part of the comparison.
if (($(this).attr("id") === 'search') || (opening == true)) return false;
My guess is that === does not exist.
== is for testing equality
so if ($(this).attr("id") === 'search' || opening == true) return false;
should be if ($(this).attr("id") == 'search' || opening == true) return false;

Javascript: How to check if a string is empty? [duplicate]

This question already has answers here:
How do I check for an empty/undefined/null string in JavaScript?
(52 answers)
Closed 3 years ago.
I know this is really basic, but I am new to javascript and can't find an answer anywhere.
How can I check if a string is empty?
I check length.
if (str.length == 0) {
}
If you want to know if it's an empty string use === instead of ==.
if(variable === "") {
}
This is because === will only return true if the values on both sides are of the same type, in this case a string.
for example:
(false == "") will return true, and (false === "") will return false.
This should work:
if (variable === "") {
}
But for a better check:
if(str === null || str === '')
{
//enter code here
}
if (value == "") {
// it is empty
}

Categories