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"
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))
What is the difference in using typeof === or typeof == or is same thing?, since both return the same value.
function main() {
var number = 10;
console.log(typeof number == 'number'); // true
console.log(typeof number === 'number'); // true
}
main();
The typeof operator always returns a string. The === compares both the value and the type whereas == operator only compares the value.
This means both the == and === comparators will always act the same when you have typeof and a string on two sides of them.
Prefer using the strict equality comparison === as is a subset of the ==. The latter does type conversations like null and undefined being equal which can be surprising.
=== makes a strict comparison and only returns true if the compared elements have the same value and type
== compares only in terms of values, not type of data
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
Javascript if statement needs refactoring due to bad data from my database.
I want a nicer way of doing this if statement:
if (typeof value === undefined || value === null || value === "" || value === 0) {
return false;
}
Is there a shorter way?
I look forward to your suggestions.
Is there a shorter way?
Only slightly:
if (value == null || value === "" || value === 0) {
...because both undefined and null are == null (and nothing else is).
Alternately, in ES2015 you could use a Set of values you want to filter:
let badValues = new Set([undefined, null, "", 0]);
then
if (badValues.has(value)) {
If you also are happy filtering out false and NaN, then you can just use
if (!value) { // Does more values than your question asks for, see note above
Note that your first condition is wrong: If you use typeof value then undefined must be in quotes, because typeof always returns a string.
You could even do something like this:
return Boolean(value);
Note that:
!!null === false
!!"" === false
!!0 === false
!!undefined === false
You can just write:
if (!value || !value.length) {return false}
if (!value) return false;
proof - >
console.log(!undefined, !null, !"", !0);
returns -> true true true true
console.log(!100, !"hello", !"0", !"false", !"true");
returns -> false false false false false
Javascript automatically transform into boolean other variables types in if statement, you can do something like this:
if (!value || !value.length) {
return false;
}
undefined, null and 0 are transformed into "false", meanwhile with .length, if it is 0 you will still have false, otherwise another number will be true.
Cheers
EDIT
for avoiding the object {length:0} to be parsed as empty, you can add:
if (!value || ((value instanceof Array || typeof value === 'string') && !value.length)) {
return false;
}
undefined and null are falsy in javascript but,
var n = null;
if(n===false){
console.log('null');
} else{
console.log('has value');
}
but it returns 'has value' when tried in console, why not 'null' ?
To solve your problem:
You can use not operator(!):
var n = null;
if(!n){ //if n is undefined, null or false
console.log('null');
} else{
console.log('has value');
}
// logs null
To answer your question:
It is considered falsy or truthy for Boolean. So if you use like this:
var n = Boolean(null);
if(n===false){
console.log('null');
} else{
console.log('has value');
}
//you'll be logged null
You can check for falsy values using
var n = null;
if (!n) {
console.log('null');
} else {
console.log('has value');
}
Demo: Fiddle
Or check for truthiness like
var n = null;
if (n) { //true if n is truthy
console.log('has value');
} else {
console.log('null');
}
Demo: Fiddle
A value being "falsy" means that the result of converting it to a Boolean is false:
Boolean(null) // false
Boolean(undefined) // false
// but
Boolean("0") // true
This is very different from comparing it against a Boolean:
null == false // not equal, null == true is not equal either
undefined == false // not equal, undefined == true is not equal either
// but
"0" == true // not equal, however, `"0" == false` is equal
Since you are using strict comparison, the case is even simpler: the strict equality comparison operator returns false if operands are not of the same data type. null is of type Null and false is of type Boolean.
But even if you used loose comparison, the abstract equality algorithm defines that only null and undefined are equal to each other.
Depending on what exactly you want to test for, you have a couple of options:
if (!value) // true for all falsy values
if (value == null) // true for null and undefined
if (value === null) // true for null
In general you should always prefer strict comparison because JS' type conversion rules can be surprising. One of the exceptions is comparing a value against null, since loose comparison also catches undefined.
=== checks for identity - the exact same type and value. So null !== false firstly because they are not the same type, thus will not match when using ===.
If you just want to check for any falsey value, then check with:
if (!n)
If you want to specifically check for null, then check for null like this:
if (n === null)