Javascript AND OR operators and parentheses - javascript

Having issues correctly triggering code in an if and or statement. I want the code in the statement to run when the defholdid var is equal to "cb_SR" AND if ANY of these variables are true: altRighttargets, inRightTargets, safetyRightTargets. I have checked each variable on their own and they all receive the values I expect. Here's the statement:
if (defholdid === "cb_SR" && (altRightTargets === true || inRightTargets === true || safetyRightTargets === true)) {
//code I want to trigger
};
I checked the statement with each individual expression, and I can get the code to trigger, so I think I'm incorrectly writing the statement.
Thanks,

Make sure that the variables you're comparing with true actually hold boolean values, not strings "true" or "false". If they contain these strings, the comparison with true will always be false. In the context of your OR grouping, that variable is effectively ignored.
The strict equality operator === will always be false for values of different types. But even if you change to the loose equality operator ==, true == "true" will be false. When comparing a boolean with another type, the boolean is converted to 0 or 1 first, and then this is compared with the other value (with additional type juggling possible). So true == "1" is true because 1 == "1", but true == "true" is false because 1 == "true" is false. As pointed out in this answer, we have the following cases of comparing a boolean with a string:
true == "true"; //false
true == "1"; //true
false == "false"; //false
false == ""; //true
false == "0"; //true

Related

JavaScript If statement not operating correctly

Below is my code and it always returns the IF statement as if it's false. Shouldn't it be true?
The variables asscostied with the IF statement:
var coloredUI = '';
var coloredText = '';
And here's the IF statement:
if (coloredText && coloredUI == '') {
} else {
}
In JavaScript, values can be "truthy" or "falsy". You set both your variables to empty strings, which are "falsy" (no characters == false). Other falsy values are:
undefined, 0, false, null
An if statement always wants to test a condition for a truthy Boolean result. If you give it an expression, that expression is evaluated, and if the result is not a Boolean, the JavaScript engine will coerce it into one. Falsy values become false and truthy values become true, so:
if(coloredText) {}
Evaluates to:
if(false) {}
because coloredText was intialized to a falsy value (''). And because you used the short-circuited logical AND, both expressions would have to be true for the entire if to be true. But, since the first one was coerced to false, the if statement proceeds to the false branch.
To avoid this, you can write an expression that compares the expression rather than coerces it alone, as in:
if(coloredText == '') // true
This concept of implicit type coercion is also why JavaScript provides two mechanisms for equality testing. Take this for example:
var x = 0;
if(x == false)
This will result in true because the double equal sign means equality with conversion. The false is converted to a number (0) and then checked against the number (0), so we get true.
But this:
var x = 0;
if(x === false)
will result in a false result because the triple equal sign means strict equality, where no conversion takes place and the two values/expression are compared as is.
Getting back to your original scenario. We leverage this implicit type coercion often when checking for feature support. For example, older browsers don't have support for Geolocation (they don't implement the object that provides that feature). We can test for support like this:
if(navigator.geolocation)
If the navigator object doesn't have a geolocation property, the expression will evaluate to undefined (falsy) and the if will head into its false branch. But, if the browser does support geolocation, then the expression will evaluate to an object reference (truthy) and we proceed into the true branch.
Empty string('') is falsey value
Following example will test whether both the values holds truthy values.
var coloredUI = '';
var coloredText = '';
if (coloredText && coloredUI) {
alert('if');
} else {
alert('else');
}
To test both values as ''
var coloredUI = '';
var coloredText = '';
if (coloredText == '' && coloredUI == '') {
alert('if');
} else {
alert('else');
}
Truthy and Falsy Values
if (coloredText == '' && coloredUI == '') {
} else {
}
if (coloredText == '' && coloredUI == '') {
} else {
}
if ((coloredText==='') && (coloredUI == '')){
} else {
}
OR if you want to check if there is a value in coloredText then use this:
if ((coloredText) && (coloredUI == '')){
} else {
}

Can === hold when == doesn't?

Are there any cases where
x == y //false
x === y //true
is that ever possible in JS? :)
No. That's never possible. === checks for type and equality. == just checks for equality. If something isn't == it can never be ===.
It'd be impossible. == compares value, while === compares value and type. Your case would require an impossible condition.
a === b -> (typeof(a) == typeof(b)) && (value(a) == value(b))
a == b -> (value(a) == value(b))
You couldn't have the value comparisons in the == case be true while requiring the exact same comparison in === become false.
== - Returns true if the operands are equal.
=== - Returns true if the operands are equal and of the same type.
So, I'll say not possible.
Briefly, if === is true, then == will return true. If === returns false, then == may or may not return false.
Examples:
5===5 is true, which means that 5==5 also must be true.
'5'===5 is false, and '5'==5 is true.
'6'===5 is false, and '6'==5 is also false.
This behavior is because a===b checks to make sure that the value and type of a and b are equal, while a==b only checks to make sure that their values are equal.

Why doesn't empty string == null in JavaScript

I understand that both empty string and null are falsy according to the ECMAScript. If both are falsy then why doesn't the following evaluate to true?
var emptyString = '';
if (emptyString == null) {
console.log('emptyString == null');
}
else {
console.log('emptyString does not == null'); // but why?
}
both empty string and null are falsy
Yes, but that doesn't mean all falsy values would be equal to each other. NaN and 0 are both falsy as well, but they're definitely not equal. The reverse doesn't hold either, "0" == 0 but "0" ain't falsy.
The sloppy equivalence of values is defined by the Abstract Equality Algorithm and its type coercions, and null simply isn't == to anything but undefined.
The more commonly used abstract comparison (e.g. ==) converts the operands to the same Type before making the comparison.
Here, null is a falsy value, but null is not == false
The falsy values null and undefined are not equivalent to anything except themselves:
(null == false); // false
(null == null); // true
(undefined == undefined); // true
(undefined == null); // true
since the other operand is null( which is also a type in javascript ), the abstract comparison of empty string(falsy value) and null doesn't give a truthy value.
I think this will help you.
Comparison Operators
and this too
Truthy and Falsy: When All is Not Equal in JavaScript

Why is 1===1===1 false?

In a browser console, entering 1===1 evaluates to true. Entering 1===1===1 evaluates to false.
I assume that this is because of the way the statement is evaluated:
1 === 1 === 1
becomes
(1 === 1) === 1
which evaluates to
true === 1
which is false.
Is this correct? If not, what's the real reason for this behaviour?
Yes, you're exactly right. Here you have two equality checks, which have the same operator precedence. First one evaluates first, then its result applies to the next equality check.
1===1===1is the same as (1===1)===1 which is true===1 which is false, because here you check by values AND their types. 1==1==1 will result in true, because it checks equality by values only, so 1==1==1 equal to (1==1)==1 equal to true==1 equal to true.
The === operator doesn't just test equality, but also type equality. Since an integer is not a boolean, true === 1 is false.
Compare:
true == 1; // true
true === 1; // false
Example.
Correct behaviour. Since
1===1 // value is true
but
true===1 // it's false
There are two reasons for this:
true is a boolean type where 1 is integer
simply, 1 is not equal to true.
so
1===1===1 // false
The behaviour that you mentioned is correct.
Its because === implies matching based on type and value.
true === 1 does not match on type, but true == 1 matches based on value.
if 1==1==1 then it will be true

Is {} == true or not in javascript?

Can someone explain why in javascript,
alert({} == true) shows false
if ({}) alert('true') shows true ?
What's different in the if condition that changes the result?
I wanted to write some shorthand argument validator obj || (obj = {}); and I was baffled by this discovery.
if ({}) alert('true') -> true
{} is an object, which, when evaluated in the context of an if statement, gets coerced to a Boolean, and since Boolean({}) evaluates to true, you get if (true). This is documented in the ECMAScript specification, Section 12.5 The if Statement:
The production If Statement : if ( Expression ) Statement is evaluated
as follows:
Let exprRef be the result of evaluating Expression.
If ToBoolean(GetValue(exprRef)) is false, return (normal, empty, empty).
Return the result of evaluating Statement.
alert({} == true) -> false
This one is more tricky. From the ECMAScript specification, Section 11.9.3 The Abstract Equality Comparison Algorithm:
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
Thus, {} == true will be evaluated as {} == Number(true), which is evaluated to {} == 1, which is false.
This is also why 1 == true evaluates to true, but 2 == true evaluates to false.
{} is not true so it won't show up in your first example. In your second example {} is not false so it will pass the test.
Like my teacher used to say, you can't compare potatoes and carrots.
It's not only with arrays, it will work with anything:
alert(3 == true); // shows false
if (3) alert('true'); // shows true
In boolean operations, generally anything that is not 0 evaluates to true.
http://jsfiddle.net/QF8GW/
if (0) console.log("0 shows true"); // does not log a value
if (-1) console.log("-1 shows true");
if (12345) console.log("12345 shows true");
if ({}) console.log("{} shows true");
if ([]) console.log("[] shows true");
All of these except 0 will evaluate to true.
However, their values, when compared to true will not evaluate to true.
// logs the statement (1 and true are the same.)
​if (1 == true) console.log("1==true shows true");​​​​​​​​
if (12345 == true) console.log("12345==true shows true"); // does not log
I tried in jsfiddle.net and only try in the first alert says false, the IF does not alert true.
alert({} == true) //display "false"
if({} == true)
{
alert("it's true");
}else
{
alert("it's false"); // <-- alert this
}
( snippet )

Categories