I got an "if" statement and i want to check if one textcontent of the variable is different from A or from B
but this doesnt seem to work
Any suggestion ??
if ( el[0].textContent != "A" || "B")
if ( el[0].textContent != "A" || el[0].textContent != "B")
if ( el[0].textContent != "A" && el[0].textContent != "B")
2nd solution from Phil_1984_
Check this out.
You have to declare to your variable both of the "things" you need to check.
and after this you will have the result you want.
Related
Is there an elegant way to check if variable is NOT falsy but in case of 0 it passes. The issue with this way of verifying
if(var !== undefined && var !== null)
is that it's long and doesn't cover all cases like undecalred or NaN. I'm also using typescript and declare it as optional number.
You can do exactly what your first sentence asks:
if (!x && x !== 0)
means literally "if x is falsy and x is not 0".
Also the == and != comparison operators explicitly consider null and undefined to be equal, so
if (x != null)
is true for both null and undefined. (That's !=, not !==.)
function Check(input) {
if (!input && input!==0){
return "falsy";
}
else if (input === 0){
return "zero";
}
}
console.log(Check(0));
console.log(Check(false))
I want to write an if/else statement that tests if the value of a text input does NOT equal either one of two different values. Like this (excuse my pseudo-English code):
var test = $("#test").val();
if (test does not equal A or B){
do stuff;
}
else {
do other stuff;
}
How do I write the condition for the if statement on line 2?
Think of ! (negation operator) as "not", || (boolean-or operator) as "or" and && (boolean-and operator) as "and". See Operators and Operator Precedence.
Thus:
if(!(a || b)) {
// means neither a nor b
}
However, using De Morgan's Law, it could be written as:
if(!a && !b) {
// is not a and is not b
}
a and b above can be any expression (such as test == 'B' or whatever it needs to be).
Once again, if test == 'A' and test == 'B', are the expressions, note the expansion of the 1st form:
// if(!(a || b))
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')
ECMA2016 answer, especially good when checking against multiple values:
if (!["A","B", ...].includes(test)) {}
In general it would be something like this:
if(test != "A" && test != "B")
You should probably read up on JavaScript logical operators.
I do that using jQuery
if ( 0 > $.inArray( test, [a,b] ) ) { ... }
For a larger number of values that is checked against often, it may be more efficient to check if the value does not exist in a Set.
const values = new Set(["a", "b"]);
if(!values.has(someValue)){
// do something
} else {
// do something else
}
var test = $("#test").val();
if (test != 'A' && test != 'B'){
do stuff;
}
else {
do other stuff;
}
You used the word "or" in your pseudo code, but based on your first sentence, I think you mean and. There was some confusion about this because that is not how people usually speak.
You want:
var test = $("#test").val();
if (test !== 'A' && test !== 'B'){
do stuff;
}
else {
do other stuff;
}
This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).
switch(test) {
case A:
case B:
do other stuff;
break;
default:
do stuff;
}
var choice1 = prompt("Enter choice 1");
var choice2 = prompt("Enter choice 2");
if (choice1 === "x" && choice2 === ("a" || "b" || "c")) {
alert("Good job!");
}
Assume the user input x for choice1 and c for choice 2.
The above is a simple example to highlight my issue. I know it doesn't work but my question is why? Javascript won't compare the multiple || statements within () against choice2. Why not? The logic in my mind is choice2 is the same type and value (===) as "a" or "b" or "c".
The way I got it working was this:
(choice1 === "x" && ((choice2 === "a") || (choice2 === "b") || (choice3 === "c"));
Please help me understand why when using multiple ||'s, you need to explicitly write out each || scenario as opposed to putting a bunch within () as I tried up top. Thanks.
It just doesn't work that way, you can't compare one value against multiple other values using OR, you have to compare each value individually.
The closest you'll get is using Array.indexOf
if ( ['a', 'b', 'c'].indexOf(choice2) != -1 )
The reason it doesn't work is because OR and AND checks for a truthy value, so in
('a' || 'b' || 'c') // return "a"
a is a truthy value, so the OR never proceeds, it doesn't have to, it already has a truthy value so the expression is true, and you're left with a, the rest is discarded
In JavaScript, if you do this
var a = null;
var b = {};
var c = "haha"
var d = a || b || c;
the value of d will be b. Expressions of type var1 || var2 || var3 return with the value of first not null or not undefined value.
So, in you case choice2 === ("a" || "b" || "c") is same as writing choice2 === "a".
(object || object) syntax is something like null check operator not for condition check in javascript.
so
console.log(null || "b") would log b
console.log(undefined || "b") would log b
console.log(("a" || "b")) would log a
console.log(null || "b")
console.log(undefined || "b")
console.log(("a" || "b"))
Your condintion(below) will only work if choice2 is "a" and choice1 is "x".
if (choice1 === "x" && choice2 === ("a" || "b" || "c")) {
alert("Good job!");
}
What is in the brackets get evaluated first so ("a" || "b" || "c") will evaluate to "a" because what you are effectively saying is return either "a" or "b" or "c" so it returns "a" because that is first.
I believe what you are expecting is ("a" || "b" || "c") to act some sort of set operation but JavaScript doesn't have that feature so your code choice2 === ("a" || "b" || "c") will only ever be true if the user chose "a". The best way to compare multiple values with choice2 is to store "a","b" and "c" in an array and see if choice2 exists in it. ["a","b","c"].indexOf(choice2) != -1.
In most languages you won't even be able to compare three strings but JavaScript does everything it can to not throw exceptions so it doesn't cause the user of the website to realise there is a problem with the page so it will try and compare the three strings as you would compare three booleans but instead of returning a boolean it returns a string. I would avoid that syntax completely as it would confuse most developers not familiar with the weird ways of JavaScript.
I am using Y.one(selector).getAttribute('value'); to return the value on a page and I am having trouble dealing with cases where value="".
var check_value = Y.one(selector).getAttribute('value');
if (check_value != undefined || check_value != null || check_value != "") {
alert(check_value);
}
With all of these checks I am getting an empty alert box when the value of the element I am looking at is "". In this case since I know the value I am looking for is a number I can change the check to just look for a number > 0 and have it work but I was wondering if anyone knew of a method to check for no value for cases where I was not dealing with numeric data.
if (check_value >0) {
alert(check_value);
}
This method does work in my case.
Why don't you just check for 'truthiness' instead?
if (check_value) {
alert(check_value);
}
It's basically the same as your (intended) check, I suppose. And if you need to check for 0 (a Number), just use this:
if (check_value || check_value === 0) {
...
}
If it is an empty string, then it isn't undefined and it isn't null. Since you check if it is not undefined or not null or not an empty string, then it will pass.
Use && not ||
You might look at Y.Lang.isValue()
http://yuilibrary.com/yui/docs/api/classes/Lang.html#method_isValue
Look at the logic in plain english check_value != undefined || check_value != null || check_value != "" if it's undefined or null or "", if it's null it's not undefined, if it's blank it's not null, so everything gets through; you're looking for a logical AND instead of OR
try this:
var check_value = Y.one(selector).getAttribute('value');
if (check_value != undefined && check_value != null && check_value != "") {
alert(check_value);
}
You're seeing the alert because your if statement has OR (||) clauses. In the case that the value attribute is an empty string, the last condition (check_value != "") should fail. However, since "" is not equal to undefined the first condition has already returned true, the if statements test passes (it won't evaluate the other conditions because it doesn't need to) and the if block is executed.
I suspect you actually wanted to use AND (&&) instead.
I want to run a code only if the argument[0].recordCount is greater than zero or is NOT undefined. However, the code is ran when the argument[0].recordCound alert shows undefined.
if(arguments[0].recordCount > 0 &&
arguments[0].recordCount !== 'undefined')
{ //if more than 0 records show in bar
document.getElementById('totalRecords').innerHTML =
arguments[0].recordCount + " Records";
}
How can I test for undefined here?
When using undefined as a string you need to do so with the typeof operator.
Also, you should be checking if it's defined before any other checks on the property.
if ( 'undefined' != typeof arguments[0].recordCount && arguments[0].recordCount > 0 )
undefined is a keyword a global variable with constant value, use it without quotes:
if(arguments[0].recordCount > 0 && arguments[0].recordCount !== undefined)
But actually it would be sufficient to test only the first condition:
if(arguments[0].recordCount > 0)
because if recordCount is larger than zero, it is defined anyway.
More common is to switch the conditions and test first whether it is defined, to avoid possible errors in the following tests (not sure if this is necessary here):
if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0)
To check for a variable to be not null and not undefined,
if(thatVariable) is enough though implicit conversion can cause problem for some cases where thatVariable is empty string, or a boolean, or number 0. If implicit conversion is not the case for our variable, the following would do,
if(arguments[0].recordCount && arguments[0].recordCount > 0)
But the following would be problematic,
if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0)
Consider,
var undefined = 'surprise' //possible since undefined is not a keyword
if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0)
Now this 'if' will break even though recordCount is undefined.
One more thing: if(a != null) will also check undefined due to implicit conversion. Hence if(a != null && a != undefined) is redundant