I think I'm missing something basic here. Why is the third IF condition true? Shouldn't the condition evaluate to false? I want to do something where the id is not 1, 2 or 3.
var id = 1;
if(id == 1) //true
if(id != 1) //false
if(id != 1 || id != 2 || id != 3) //this returns true. why?
Thank you.
With an OR (||) operation, if any one of the conditions are true, the result is true.
I think you want an AND (&&) operation here.
You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say
the id is not 1, and the id is not 2, and the id is not 3.
which translates to
if (id !== 1 && id !== 2 && id !== 3)
or alternatively for something more pythonesque:
if (!(id in [,1,2,3]))
Each of the three conditions is evaluated independently[1]:
id != 1 // false
id != 2 // true
id != 3 // true
Then it evaluates false || true || true, which is true (a || b is true if either a or b is true). I think you want
id != 1 && id != 2 && id != 3
which is only true if the ID is not 1 AND it's not 2 AND it's not 3.
[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.
When it checks id!=2 it returns true and stops further checking
because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.
This is an example:
false && true || true // returns true
false && (true || true) // returns false
(true || true || true) // returns true
false || true // returns true
true || false // returns true
Related
This question already has answers here:
Why does new Number(2) != new String("2") in JavaScript
(3 answers)
Closed 5 years ago.
On comparing string text to string object using ( == ) operator, returns true
var o = new String("ss");
var s = "ss";//return "ss" (string)
console.log(o);//return object
console.log(o==s);//return true
How can i understand that?
That's because == is only comparing the value of o and s. === would compare the value and the type.
A little example:
console.log(1337 == "1337"); // true
console.log(1337 === "1337"); // false
console.log(1 == true); // true;
console.log(1 === true); // false
console.log("string" == new String("string")); // true
console.log("string" === new String("string")); // false
console.log(undefined == null); // true
console.log(undefined === null); // false
The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.
JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
exemple:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
you can see the details in this link :link
I have some JavaScript on my page that checks the indexOf to find one of a multitude of strings in my URL, it then performs a function that scrolls to a set position on the page.
I currently am using the following code to concatenate 2 conditions, but I need to incorporate a 3rd condition. When I add an additional line and an additional && my JavaScript fails. Can anyone recommend a better solution?
My current working code:
if (window.location.href.indexOf("search_categories") > -1 &&
window.location.href.indexOf("search_region") > -1) {
// do some stuff
};
The failing code:
if (window.location.href.indexOf("search_categories") > -1 &&
window.location.href.indexOf("search_region") > -1 &&
window.location.href.indexOf("upload-a-cv") > -1) {
// do some stuff
};
I would not call this concatenation. The double ampersand represents the logical AND operator. In general you can have as many operands as possible:
operand1 && operand2 && operand3 ...
Each operand should be, or at least should be evaluated to a boolean value - true or false. The logical result is applied on the evaluated boolean values as follows:
Logical AND ( && )
true && true = true
true && false = false
false && true = false
false && false = false
This means that if any operand is evaluated to false, the whole evaluation is resulting as false (true && true && false becomes false in the end).
In case you want to allow any condition (operand) to cause the result to be true, you would have to use the
Logical OR ( || )
true || true = true
true || false = true
false || true = true
false || false = false
Effectively false || false || false || true evaluates to true
If you want to have certain groups of conditions to be all true, and the another group where at least one is true, you have to group them, using braces as in:
-(true && false) || (false || true) evaluates to true
-(true && false) && (false || true) evaluates to false
In your particular code snippet:
if (window.location.href.indexOf("search_categories") > -1 &&
window.location.href.indexOf("search_region") > -1 &&
window.location.href.indexOf("upload-a-cv") > -1 ) ...
it is enough to lack at lease one of the parameters in the request, to have the if expression evaluate to false, therefore the body of the if statement does not get executed.
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 does the && operator return the last value (if the statement is true)?
("Dog" == ("Cat" || "Dog")) // false
("Dog" == (false || "Dog")) // true
("Dog" == ("Cat" && "Dog")) // true
("Cat" && true) // true
(false && "Dog") // false
("Cat" && "Dog") // Dog
("Cat" && "Dog" && true) // true
(false && "Dog" && true) // false
("Cat" && "Dog" || false); // Dog
Fiddle
Logical Operators - && (MDN)
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both
operands are true; otherwise, returns false.
For your expression "Cat" && "Dog" , the first expression "Cat" can't be converted to false or a boolean value, hence it returns "Dog"
Think of && in JavaScript like this (based on ToBool from the es5 spec)
function ToBool(x) {
if (x !== undefined)
if (x !== null)
if (x !== false)
if (x !== 0)
if (x === x) // not is NaN
if (x !== '')
return true;
return false;
}
// pseudo-JavaScript
function &&(lhs, rhs) { // lhs && rhs
if (ToBool(lhs)) return rhs;
return lhs;
}
Now you can see that ToBool("Cat") is true so && will give rhs which is "Dog", then === is doing "Dog" === "Dog", which means the line gives true.
For completeness, the || operator can be thought of as
// pseudo-JavaScript
function ||(lhs, rhs) { // lhs || rhs
if (ToBool(lhs)) return lhs;
return rhs;
}
Why does the && operator return the last value?
Because that's what it does. In other languages, the && operator returns the boolean true or false. In Javascript, it returns the first or second operand, which is just as well since those values themselves are "truthy" or "falsey" already.
Hence 'Cat' && 'Dog' results in the value 'Dog', which is equal to 'Dog'.
Because you asked if true === (true && true). If you use a non Boolean in a Boolean operation, javascript will convert to Boolean. Non empty strings are "true" so it returns correct.
I'm guessing the language designers wanted to enable users to use the || operator as a "coalesce" operator, in the style of e.g. the "null coalesce" operator ?? in C#.
In other words, if you want a default value, you can use the following idiom:
var x = input || "default";
//x will be equal to input, unless input is falsey,
//then x will be equal to "default"
Is there a special reason to do:
if (!options || (options && options.booleanCondition))
Instead of:
if (!options || options.booleanCondition)
I'm no javascript guru, so perhaps there's a special case or reason why the author of that code wrote it that way.
i don't see a reason to do
if (!options || (options && options.booleanCondition))
I'm no Guru but i'd stick to
if (!options || options.booleanCondition)
and save a check to the fact that options is true: in fact if options is not true the first condition is true and the second is never evaluated since it's an or condition.
That's what i think
Perhaps it's using a getter. This is a rediculous example but it can be the reason:
var o = {};
var i = 0;
o.__defineGetter__('options', function() {
return (i++) % 2 === 0 ? {booleanCondition: true} : null;
});
o.options; // Object first time
o.options; // null second time
This means:
if (!o.options || (o.options && o.options.booleanCondition))
!o.options is false (negating an object), but after that o.options is null (falsy) so then the check is mandatory.
if options.booleanCondition can change, then yes. If options is false, then the If condition will be true. If options is true, and boolean.Condition is false, then the If condition will be false. If option is true, and boolean.Condition is true, then the If condition will be true.
UPDATE
Actually, I guess it wouldn't be needed - since your simplification would be (if !true or true) if options is true, so the result would be same as (if true or true).