Can't make multiple if conditions in JavaScript? - 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;

Related

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

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

Evaluate a boolean condition stored as a string

I have several thousand entries in a database that were scraped from a website. They are strings which list conditions which must be met. For example: "(Thing1 and Thing2) or (Thing3 and Thing4)"
I would like a user to enter a list of conditions they have, and then check them against the database. Due to the fact that these strings come from a trusted site, and are so close to valid boolean conditions already I'm tempted to put them in an eval() statement. I could parse the string, find the conditions, check if they are true, and replace them with 1 or 0. Then replace (and, or) with (&&, ||). Then I would check to make sure everything at that point is one of: space, 1, 0, &, |, (, or ). If not, log the error in some way. If it is just those characters do:
eval("Boolean((1 && 0) || (0 && 0))")
I realize eval() is generally a bad idea, so I'm open to other ideas. However, in this case I feel the security is increased if I check for just those characters before running the eval, and since the input is data scraped from a trusted site.
I'm planning on doing this in javascript, but could also do it in PHP on the server.
If you really want to avoid eval() at all cost, you could use something like this:
function evalBoolean(str) {
while (str.length > 1) {
str = str.replace(/0 && 0|0 && 1|1 && 0|0 \|\| 0|\(0\)/g, "0");
str = str.replace(/1 && 1|0 \|\| 1|1 \|\| 0|1 \|\| 1|\(1\)/g, "1");
}
return (str == "1");
}
alert(evalBoolean("((0 && 1) || (1 && 1))"));
alert(evalBoolean("(((0 || 1) && (0 || 0)) && ((1 || 1) || 0))"));
If you think there could be malformed input, use this safer version which returns undefined if it can't resolve the expression.
function evalBoolean(str) {
var len;
while (str.length > 1) {
if (str.length == len) return; else len = str.length;
str = str.replace(/0\s*&&\s*0|0\s*&&\s*1|1\s*&&\s*0|0\s*\|\|\s*0|\(\s*0\s*\)|\s*0\s*/g, "0");
str = str.replace(/1\s*&&\s*1|0\s*\|\|\s*1|1\s*\|\|\s*0|1\s*\|\|\s*1|\(\s*1\s*\)|\s*1\s*/g, "1");
}
return (str == "1");
}
alert(evalBoolean(" (( (0|| 1) &&(0 || 0) )&& ( (1||1) ||0))"));
alert(evalBoolean("((1 && 0) && 1 )) ( && 1"));

raising onkeypress element when input value is null

i am developing a chat application with user-typing and user-erasing functionality but i am having difficulties in calling a function when the textarea chat input is null( when the user erase all what he typed )
var msg=$("#chat_input").val();
if ((e.which== 8 || e.keyCode == 8) && (msg.trim() == "" || msg.length <= 1)) {
// call the function
}
when a user type one letter and then erase it the function is not called and this if statement is false
how can i fix this
Backspacing the last character or only having new lines or spaces means this.value will return false
$('#chat_input').keyup(function(e){
if (e.which == 8 && this.value == false) {
}
});
jsFiddle Demo
value is false if is just a space, newline etc, so you don't need trim()
( msg.length <= 1 ) // = true when second to last or last
You can simplify this by using implicit true/false checks
var msg=$("#chat_input").val();
if (e.which== 8 && (!msg || !msg.trim())) {
// call the function
}
!msg will return true if msg is undefined or null and !msg.trim() will return true if msg.trim() is an empty string.

can "or" be used in the logical test for a while loop?

Not sure why this only seems to work with the response "yes"(or "Yes"/"YES") - any help would be appreciated. Pretty new to this!
var yesNo = window.prompt("Are you from Earth?");
var lowerYesNo = yesNo.toLowerCase();
while (lowerYesNo != ("yes" || "no")){
yesNo = window.prompt("Please answer with \"Yes\" or \"No\". Are you from Earth?");
lowerYesNo = yesNo.toLowerCase();
}
switch (lowerYesNo){
case "yes":
window.alert("I thought so!");
break;
case "no":
window.alert("Capture the alien!!!");
break;
default:
window.alert("I don't know how you got this to display!");
}
"yes" || "no"
returns "yes", because it is a "truthy" value and therefore the first operand of || is returned.
If you want to compare to both values, you will need to split this into two separate comparisons:
while (lowerYesNo != "yes" && lowerYesNo != "no")) {
//...
The correct way to write that is
while (lowerYesNo !== 'yes' && lowerYesNo !== 'no') {
// ...
}
you can try this,
((lowerYesNo != "yes") && (lowerYesNo != "no")){
what you probably wanted to do was:
while (!(lowerYesNo == "yes" || lowerYesNo == "no")){
...
that's same as
while (lowerYesNo != "yes" && lowerYesNo != "no"){
...
Meanwhile, take note:
(x || y) // this expression will return x, if x is truthy otherwise y
and
(x && y) // this expression will return x, if x is falsy, otherwise it returns y
Hence the loop in your question is equivalent to this:
while (lowerYesNo != "yes"){
... // you must say "yes" else you're stuck in here.
}
Yes it can be but it needs to be a whole expression
while( expression1 || expression2)
So in your case it would be
while (lowerYesNo != "yes" || lowerYesNo != "no")
though as has been pointed out in this instance you probably want to use an &&, since you are trying to print the message only if it is (NOT yes AND NOT No)
Because evaluation of the expression
"yes" || "no"
results in
"yes"
according to javascript rules in evaluating the "or" operator.

function not executing on comparison of two arrays

I am trying to get a comparison operator to work, without success. The operator compares two arrays to ensure they are identical.
if (($(array_1).not($(array_2)).length === 0 && $(array_2).not($(array_1)).length === 0)) {
alert("all matches dropped");
}
The code works of course with 'true' in place of the comparison.
if (true) {
alert("all matches dropped");
}
The strange part is that the comparison returns 'true' when entered into the console:
console.log($(array_1).not($(array_2)).length === 0 && $(array_2).not($(array_1)).length === 0)
----> true
Any ideas what may be wrong? Thanks.
It should be:
if($(array_1).not(array_2).length === 0 && $(array_2).not(array_1).length === 0)
Instead of:
if (($(array_1).not($(array_2)).length === 0 && $(array_2).not($(array_1)).length === 0))
Here $(array_1).not(array_2).length and ($(array_1).not($(array_2)).length both are not the same thing.

Categories