OR in ternary operator, using && - javascript

Using the traditional if statement I can do this:
if(a===0 || b===0) {console.log('aloha amigo')};
But when I try to do something the same thing with a ternary operator, like this:
a===0 || b===0 && console.log('aloha amigo')
I just get errors about unexpected ||.
According to this answer: Precedence: Logical or vs. Ternary operator, we can do it using
condition1 || condition2 ? do if true : do if false
(Sorry I'm not sure how to call the ? : symbols in this case), but I'm not sure how to get it running using && (It means only run the code if returned true).
I created a codepen to test it easily. Here's the whole code:
var a = 0;
var b = 1;
a===0 || b===0 ? console.log('Works here') : console.log('And here');
a===0 || b===0 && console.log('Doesn\'t work here');
a===0 && console.log('The && works for a single test');
Here's the link

Just take parenthesis to prevent operator precedence of && over ||
(a === 0 || b === 0) && console.log('aloha amigo')
Without parenthesis, you get (now with to show the precedence) a different result.
a === 0 || (b === 0 && console.log('aloha amigo'))
^^^^^^^ first evaluation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ second evaluation

Related

Check if a getElementById is empty

I have a if else function in javascript:
if(document.getElementById('lengthFront').value > 4 && document.getElementById('lengthFront').value < 296 && document.getElementById('lengthBack').value > 4 && document.getElementById('lengthBack').value < 296)
{
document.getElementById('param_length').classList.remove('bg-danger');
}
else
{
document.getElementById('param_length').className = "bg-danger";
}
Bu I need an extra check so it won't be executed when lengthFront or lengthBack is empty, I have tried different solutions but I can't find the right way to get it working. All my solutions are pointing to else
I have tried to add:
document.getElementById('lengthFront') == '' && document.getElementById('lengthBack') == '' &&......
document.getElementById('lengthFront') == false && document.getElementById('lengthBack') == false &&......
document.getElementById('lengthFront') == null && document.getElementById('lengthBack') == null &&......
document.getElementById('lengthFront') =!= undefined && document.getElementById('lengthBack') != undefined &&......
Any suggestions
if(document.getElementById('lengthFront') && document.getElementById('lengthFront').value != '')
First condition makes sure that the element exists, second one makes sure it's value is not empty.
For the most concise and readable approach to dealing with DOM elements that may or may not exist and that may not have a valid value if they do exist, might I suggest you leverage two friends: logical AND && which you can use as a faux null coalescing operator, and the 'conditional ternary' operator ?: in such a way that you can check for null and blank string, and then assign a default value (0) or the element value, all in the initial assignment statement. Also, you'll want to avoid multiple redundant getElementByXXX queries by simply assigning the result to a variable (better readability, less typing, performs faster):
var lengthFront = document.getElementById('lengthFront');
var lengthBack = document.getElementById('lengthBack');
var paramLength = document.getElementById('param_length');
lengthFront = (lengthFront && lengthFront.value != '') ? lengthFront .value : 0 ;
lengthBack = (lengthBack && lengthBack.value != '') ? lengthBack .value : 0 ;
if(lengthFront > 4 && lengthFront < 296 && lengthBack > 4 && lengthBack < 296) {
paramLength && paramLength.classList.remove('bg-danger')
} else {
paramLength && (paramLength.className = "bg-danger");
}

Adding the OR operator to a quizz form makes it accept any answers

I'm having a weird problem when trying to create a question form that is validated with Javascript:
If I write my validation like this:
if (typedValue === "myAnswer" && clearedLevels === 1){doStuff}
Everything works. But I want to create several correct answers, so I write:
if (typedValue === "myAnswer"||"secondAnswer" && clearedLevels === 1){doStuff}
..and all of a sudden anything written to the input form is accepted as the answer.
A correct way of writing it is :
if ((typedValue === "myAnswer" || typedValue === "secondAnswer") && clearedLevels === 1) { doStuff() }
You cannot combine the condition (x === y || x === z) as x === y || z and expect the same results.
Any non-empty string in Javascript is true (yes, even the string "false"). Since "secondAnswer isn't empty, it's evaluated as true, and ORed with any other condition will result in true.
You are missing a comparison of typedValue to this literal, and presumably, brackets around the typedValue comparisons, since && has higher precedence than ||:
if ((typedValue === "myAnswer" || typedValue === "secondAnswer") &&
clearedLevels === 1) {
// doStuff
}
extending Akash Pradhan answer you could write
if (typedValue == "myAnswer" || typedValue == "secondAnswer" && clearedLevels == 1) { doStuff() }
but since the && has precedence over the || operator it would evaluate
if (typedValue == "myAnswer" || (typedValue == "secondAnswer" && clearedLevels == 1)) { doStuff() }

Why is this '=' syntax incorrect in this js snippet?

var hungry = true;
var foodHere = true;
var eat = function() {
if (hungry && foodHere === true) {
return(true);
} else {
return(false);
}`
};
The first line is the correct syntax. For a long time I was just saying hungry && foodHere = true... and I couldn't figure out (and still don't understand) why that is wrong. I understand the difference between = (assignment) and === (equal to). I assigned the variables to be true initially, so aren't I asking in the if statement if that's what they're set to? Why am I setting the variables = to in the var definition, but then when checking them I'm using the === value?
= is only used to assign variables. === or == are used to compare. For a good example, we must look into comparison operators.
Syntax
The syntax of comparison operators is fairly simple, use them to evaluate expressions. The comparasin operators are:
=== //strict equality
== //Parsed or partial equality
> //Greater Than
< //Less than
>= //Greater than or equal to
<= //Less than or equal to
To properly use these, you must know the proper syntax. For example, I can't do something like:
if(true == 1 === true) //do something
as that would invalidate the code, and slow it down by much using ==, which brings me to my next section.
Equality
The two equality operators in JavaScript are == and ===. They do two very different things.
===
The strict equality (===) tests whether two values are exactly equivalent, both in type and value.
==
The Parsed equality (==) tests whether two values are equalivent in value, but parses to try and connect different types.
Inequality
There are 2 main inequality value in JavaScript (!==) they are pretty self explainatory based on the equalities (===, and ==)
here's a chart explaining the three.
1 0 true false null undefined ""
1 === !== == !== !== !== !==
0 !== === !== == == == !==
true == !== === !== !== !== !==
false !== == !== === == == ==
null !== == !== == == == ==
undefined !== == !== == == === !==
"" !== == !== == == !== ===
Adding onto what #jcollum said, = defines a variable value, and if(something === true) simplifies into if(something). Similarly, if(something === false) simplifies into if(!something).
You also need to do comparisons separately. if(7 & 6 < 10) returns false because it is the simplified version of if(7 === true && 6 < 10).
It turns:
hungry && foodHere === true
into
hungry && true
or just
hungry
Using the assignment operator instead of the comparison operator is stopping your logic from working correctly.

Lost in javascript comparisons

I'm writing a script to be executed when my body element hasn't got any of the following classes:
a OR b OR c AND d
I tried this, but it doesn't seem to do the trick:
if ((!$('body').hasClass('a')) || (!$('body').hasClass('b')) || ((!($('body').hasClass('c')) && (!$('body').hasClass('d'))))) {
}
UPDATE
This seems to work:
if (!($('body').hasClass('a') || $('body').hasClass('b') || $('body').hasClass('c') && $('body').hasClass('d'))) {
}
use
$(function(){
if ((!$('body').hasClass('a')) || (!$('body').hasClass('b')) || !($('body').hasClass('c') && $('body').hasClass('d'))) {
}
});
You are looking for a body that doesnt have any of the classes, so you need to use &&. Heres what happens:
if(hasclass(a) || hasclass(b)) = if(true OR false) = if(true)
Above the OR operator || means that once it hits a true evaluation, it will execute your if-block.
if(hasclass(a) && hasclass(b)) = if(true AND false) = if(false)
Here the AND operator && means that once you hit a false evaluation, you block won't be executed.
You want the last thing to happen, since you want it to have neither of the classes. Learn how to play with these operators as they can be very confusing. As long as you remember that the AND operator will execute only if all statements are true and the OR operator will only execute if one of the statements is true. Nested operators work the same, so if((a = b && b = c) || (a = c)) will execute if a,b and c are the same OR when a and c are the same, but not when a and b are the same or a and c are the same.
More on expression and operators (specifically Bitwise and a must read): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators

If condition checking for two TextFields Value

if(a.value === undefined || a.value.length>37 ||
b.value === undefined || b.value.length > 256) {
If the first one is undefined or greater than a length of 37. I get a error, but it does not check for the second field at all.
use parenthesis. It checks from left to right and stops once it hits a fail the way you have it set up.
Try
if((a.value === undefined || a.value.length>37) ||
(b.value === undefined || b.value.length > 256)) {
Conditional evaluation is lazy, i.e. it stops as soon as the result has been determined. That is, if (A && B) will not evaluate B if A is false, because the conjunction will have to be false already, and similarly if (A || B) will not evaluate B if A is true because the disjunction is already true.
You're forgetting what an OR in logic means. It only going to check until it finds one true statement.
Try regrouping:
((a.value === undefined || a.value.length>37)
||
(b.value === undefined || b.value.length > 256))
Just about elevating the condition a bit, and bringing a more broad result back instead of chasing the first true response.

Categories

Resources