I saw in a pull request that the double negation operator (!!) is used for the focus attribute of a text field as follows:
focused: !!value || value === 0,
As far as I know, the operator converts everything to a boolean. If it was falsy (for example 0, null, undefined,..), it will be false, otherwise, true.
In my case, i.e. if value = 0, the following comes out:
focused: false || true
The || operator here therefore makes no sense for the value 0 or am I completely confused?
It looks like a check for numbers to get false for '', "", false, NaN, undefined and null. Other bjects, like functions, arrays or simple objects returns true;
const check = value => !!value || value === 0;
console.log(check(0));
console.log(check(1));
console.log(check(''));
console.log(check(""));
console.log(check(false));
console.log(check(NaN));
console.log(check(null));
console.log(check(undefined));
console.log(check({}));
Related
I am calling two functions and checking if the given input has barcode and qr code
var decode = jsQR.decodeQRFromImage(rawImageData.data, rawImageData.width, rawImageData.height);
checkBarCode(function(err, result) {
if (result) {
Result.pages.push({
ValidTicket: decode ? true : false //here i want to assign true or false if barcode or qr code is present.
});
}
});
is this correct?
ValidTicket: decode || result ? true : false
Your assignment does work correctly, but I might suggest using two boolean NOT operators instead, which is slightly terser:
var decode = jsQR.decodeQRFromImage(
rawImageData.data,
rawImageData.width,
rawImageData.height
);
checkBarCode(function(err, result) {
if (result) {
Result.pages.push({
ValidTicket: !!(decode || result)
});
}
});
Yes, that's correct. If either decode or result is truthy*, you'll assign true; if both are falsy*, you'll assign false.
You may get someone telling you to just do this:
ValidTicket: decode || result
...but that won't necessarily assign either true or false, because of JavaScript's curiously-powerful || operator (that's a post on my anemic little blog); instead, it'll assign the value of decode if it's truthy, and the value of result if not. So if you really need true or false, you need to use the conditional as you have done.
* About "truthy" and "falsy":
"truthy" - a value that coerces to true when used as a boolean
"falsy" - a value that coerces to false when used as a boolean
The falsy values are 0, "", NaN, null, undefined, and (of course), false. All other values are truthy.
I have a variable which is either set to something or is undefined. I wish to pass to a function true if the variable is defined else false. Here is the function:
function f(areRowsSelectable){...}
Which of the following would you do?
f(v);
f(v?true:false);
Or something else?
I usually use double negation (which means applying the logical NOT operator twice) for explicit boolean conversion:
!!v
Examples:
!!'test' // true
!!'' // false
!!0 // false
!!1 // true
!!null // false
!!undefined // false
!!NaN // false
Alternatively, also Boolean(v) would work.
I would use the "typeOf" guard method.
It does not accept "truthy" arguments, so it depends on your function whether you can use it.
The tests are basically the same as czosel's answer, but his answer returns "truthy" while mine only accepts boolean true as true.
var tests = [
//filled string
'test',
//empty string
'',
//Numeric empty
0,
//Numeric filled
1,
//Null
null,
//Completely undefined
,
//undefined
undefined,
//Not-A-Number numeric value
NaN,
//Boolean true
true
];
for (var t = 0; t < tests.length; t++) {
var test = tests[t];
var results = {
test: test,
isTruthy: !!test,
isBoolTrue: (typeof test != "boolean" ? false : test),
isDefined: (test !== void 0)
};
console.log(results);
}
EDIT 1
Since the question could be interpreted in several ways, i have included a couple of more tests.
isTruthy matches czosel's answer. Registers truthy values like 1 as true.
isBoolTrue was my first interpretation where it checks strictly whether a value is boolean true.
isDefined simply returns if the variable contains anything at all.
I am debugging some JavaScript and can't explain what this || does:
function (title, msg) {
var title = title || 'Error';
var msg = msg || 'Error on Request';
}
Why is this guy using var title = title || 'ERROR'? I sometimes see it without a var declaration as well.
What is the double pipe operator (||)?
The double pipe operator (||) is the logical OR operator . In most languages it works the following way:
If the first value is false, it checks the second value. If that's true, it returns true and if the second value is false, it returns false.
If the first value is true, it always returns true, no matter what the second value is.
So basically it works like this function:
function or(x, y) {
if (x) {
return true;
} else if (y) {
return true;
} else {
return false;
}
}
If you still don't understand, look at this table:
| true false
------+---------------
true | true true
false | true false
In other words, it's only false when both values are false.
How is it different in JavaScript?
JavaScript is a bit different, because it's a loosely typed language. In this case it means that you can use || operator with values that are not booleans. Though it makes no sense, you can use this operator with for example a function and an object:
(function(){}) || {}
What happens there?
If values are not boolean, JavaScript makes implicit conversion to boolean. It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.
So the above example should give true, because empty function is truthy. Well, it doesn't. It returns the empty function. That's because JavaScript's || operator doesn't work as I wrote at the beginning. It works the following way:
If the first value is falsey, it returns the second value.
If the first value is truthy, it returns the first value.
Surprised? Actually, it's "compatible" with the traditional || operator. It could be written as following function:
function or(x, y) {
if (x) {
return x;
} else {
return y;
}
}
If you pass a truthy value as x, it returns x, that is, a truthy value. So if you use it later in if clause:
(function(x, y) {
var eitherXorY = x || y;
if (eitherXorY) {
console.log("Either x or y is truthy.");
} else {
console.log("Neither x nor y is truthy");
}
}(true/*, undefined*/));
you get "Either x or y is truthy.".
If x was falsey, eitherXorY would be y. In this case you would get the "Either x or y is truthy." if y was truthy; otherwise you'd get "Neither x nor y is truthy".
The actual question
Now, when you know how || operator works, you can probably make out by yourself what does x = x || y mean. If x is truthy, x is assigned to x, so actually nothing happens; otherwise y is assigned to x. It is commonly used to define default parameters in functions. However, it is often considered a bad programming practice, because it prevents you from passing a falsey value (which is not necessarily undefined or null) as a parameter. Consider following example:
function badFunction(/* boolean */flagA) {
flagA = flagA || true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
It looks valid at the first sight. However, what would happen if you passed false as flagA parameter (since it's boolean, i.e. can be true or false)? It would become true. In this example, there is no way to set flagA to false.
It would be a better idea to explicitly check whether flagA is undefined, like that:
function goodFunction(/* boolean */flagA) {
flagA = typeof flagA !== "undefined" ? flagA : true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
Though it's longer, it always works and it's easier to understand.
You can also use the ES6 syntax for default function parameters, but note that it doesn't work in older browsers (like IE). If you want to support these browsers, you should transpile your code with Babel.
See also Logical Operators on MDN.
It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".
It's shorthand for writing:
if (!title) {
title = "Error";
}
This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:
a OR b
it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:
var title = title || "Error";
basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.
If title is not set, use 'ERROR' as default value.
More generic:
var foobar = foo || default;
Reads: Set foobar to foo or default.
You could even chain this up many times:
var foobar = foo || bar || something || 42;
Explaining this a little more...
The || operator is the logical-or operator. The result is true if the first part is true and it is true if the second part is true and it is true if both parts are true. For clarity, here it is in a table:
X | Y | X || Y
---+---+--------
F | F | F
---+---+--------
F | T | T
---+---+--------
T | F | T
---+---+--------
T | T | T
---+---+--------
Now notice something here? If X is true, the result is always true. So if we know that X is true we don't have to check Y at all. Many languages thus implement "short circuit" evaluators for logical-or (and logical-and coming from the other direction). They check the first element and if that's true they don't bother checking the second at all. The result (in logical terms) is the same, but in terms of execution there's potentially a huge difference if the second element is expensive to calculate.
So what does this have to do with your example?
var title = title || 'Error';
Let's look at that. The title element is passed in to your function. In JavaScript if you don't pass in a parameter, it defaults to a null value. Also in JavaScript if your variable is a null value it is considered to be false by the logical operators. So if this function is called with a title given, it is a non-false value and thus assigned to the local variable. If, however, it is not given a value, it is a null value and thus false. The logical-or operator then evaluates the second expression and returns 'Error' instead. So now the local variable is given the value 'Error'.
This works because of the implementation of logical expressions in JavaScript. It doesn't return a proper boolean value (true or false) but instead returns the value it was given under some rules as to what's considered equivalent to true and what's considered equivalent to false. Look up your JavaScript reference to learn what JavaScript considers to be true or false in boolean contexts.
|| is the boolean OR operator. As in JavaScript, undefined, null, 0, false are considered as falsy values.
It simply means
true || true = true
false || true = true
true || false = true
false || false = false
undefined || "value" = "value"
"value" || undefined = "value"
null || "value" = "value"
"value" || null = "value"
0 || "value" = "value"
"value" || 0 = "value"
false || "value" = "value"
"value" || false = "value"
Basically, it checks if the value before the || evaluates to true. If yes, it takes this value, and if not, it takes the value after the ||.
Values for which it will take the value after the || (as far as I remember):
undefined
false
0
'' (Null or Null string)
Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.
var title = title || 'Error';
var msg = msg || 'Error on Request';
Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:
false.
0 (zero)
"" (empty string)
null.
undefined.
NaN (a special Number value meaning Not-a-Number!)
So in the line
var title = title || 'Error';
If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).
If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.
It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.
i.e.
return ("" || undefined)
returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running
var foo = undefined
foo = foo || ""
foo would be set to ""
Double pipe stands for logical "OR". This is not really the case when the "parameter not set", since strictly in JavaScript if you have code like this:
function foo(par) {
}
Then calls
foo()
foo("")
foo(null)
foo(undefined)
foo(0)
are not equivalent.
Double pipe (||) will cast the first argument to Boolean and if the resulting Boolean is true - do the assignment, otherwise it will assign the right part.
This matters if you check for unset parameter.
Let's say, we have a function setSalary that has one optional parameter. If the user does not supply the parameter then the default value of 10 should be used.
If you do the check like this:
function setSalary(dollars) {
salary = dollars || 10
}
This will give an unexpected result for a call like:
setSalary(0)
It will still set the 10 following the flow described above.
Double pipe operator
This example may be useful:
var section = document.getElementById('special');
if(!section){
section = document.getElementById('main');
}
It can also be:
var section = document.getElementById('special') || document.getElementById('main');
To add some explanation to all said before me, I should give you some examples to understand logical concepts.
var name = false || "Mohsen"; # name equals to Mohsen
var family = true || "Alizadeh" # family equals to true
It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.
And operator have the opposite structure like below.
var name = false && "Mohsen" # name equals to false
var family = true && "Alizadeh" # family equals to Alizadeh
Quote: "What does the construct x = x || y mean?"
Assigning a default value.
This means providing a default value of y to x,
in case x is still waiting for its value but hasn't received it yet or was deliberately omitted in order to fall back to a default.
And I have to add one more thing: This bit of shorthand is an abomination. It misuses an accidental interpreter optimization (not bothering with the second operation if the first is truthy) to control an assignment. That use has nothing to do with the purpose of the operator. I do not believe it should ever be used.
I prefer the ternary operator for initialization, for example,
var title = title?title:'Error';
This uses a one-line conditional operation for its correct purpose. It still plays unsightly games with truthiness but, that's JavaScript for you.
I am currently reading JavaScript from JavaScript: The Definitive Guide. On page 76, there is this statement written,
o && o.x // => 1: o is truthy, so return value of o.x
Being a Java programmer I want to ask, why is it returning 1 instead of 'true' In Java this was not the case, but anyway I know JavaScript is different but the Logical AND mechanism is the same everywhere.(In C it returns 1 as true.)
I am asking is, why does it makes sense for this behavior at all?
Is there any way, I can ensure to return only the true or false values?
As per the Spec for Binary Logical Operators
The value produced by a && or || operator is not necessarily of type
Boolean. The value produced will always be the value of one of the two
operand expressions.
This is a feature used in javascript a lot, one common use case is to assign a default value to a variable if it is not defined. Like assume you are expecting a options object as a param but is not mandatory so the user may not pass it
function x(options){
options = options || {};
//now your can access optionx.a without fearing whether options is undefined
}
You can do something like !!(o && o.x) to always get a true/false
if we have:
expr1 && expr2
&& 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.
So if we have:
Var xyz = a && b; //where a is undefined(false) and b is 123, then it will allocate undefined.
In case of if statements, these values are specifically converted to boolean.
Refer the following link: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators"
You can use Boolean(o && o.x); to get true or false
It's returning the value of the right operand. If the value of o.x was true, it would return true. If the value of o.x was 'banana', it would return 'banana'.
var o = {x:true};
console.log(o && o.x);
Technically && operator implemented to return the first operand if it's value is not zero, and returns the second operand otherwise in a lot of languages including Java, C/C++, Javascript, Perl...
While most of the languages accepts any type of operands, Java forces you to use boolean operands so it always returns true or false.
In order to force a boolean result in Javascript use:
Boolean(a && b)
This behaviour is called coercion. Coercion is the action of forcing an object to behave like other type, and the logical operators can produce coercion when trying to access the value of the object to be evaluated.
It is important to remember the table for truthy and falsy values, because due to coercion, different results can be obtained.
false produces false
0 produces false
“” produces false
NaN produces false
null produces false
undefined produces false
Everything else produces true, including the text "0" and "false", functions, arrays and empty objects.
Given the rules for logic operators, exists short-circuit evaluation in JavaScript, e.g:
0 && 1; //-> 0, falsy value
!(0 && 1); //-> true, falsy value negated
!!(0 && 1); //-> false, boolean falsy value
void 0 && alert("1") //-> undefined (void produces undefined)
[] && Math.ceil(9.1) //-> 10, truthy value
{} && someFunc() //-> the result of someFunc()
0 || null; //-> null, falsy value
null || "0"; //-> "0", truthy value
"" || void 1; //-> undefined, falsy value
!!(+"5px" || {}); //-> true, boolean truthy value
Coercion is useful when you have to validate default values, in order to prevent errors, e.g.
function divide (a, b) {
a = +a; //-> coerced to number
b = +b; //-> coerced to number
if (!a) return 0; //-> NaN or zero
return b && a / b; //-> b must be a number different from zero
}
divide(); //-> 0
divide(5); //-> NaN, no error thrown!
divide(5, "a"); //-> NaN, no error thrown!
divide(5, 0); //-> 0, division by zero prevented!
divide(49, 6); //-> 8.1666
If you want to prevent returning NaN, just add another coercion in the return statement:
return (b && a / b) || 0;
You can check other coercion cases: JavaScript Coercion
Happy coding!
Why does the following code produce a == 3?
var x = "abc";
var y = 3;
var z = "xyz";
var a = x && y || z;
http://jsfiddle.net/thinkingmedia/qBZAL/
I would have expected this to result in a == true.
Why is the logical operator evaluating "abc" as true but doesn't evaluate 3 as true. Instead it produces 3 as the result.
Furthermore, if you change y = 0 then a == "xyz" which means that && treated 0 as false. What happen to treating a number as a number?
What's going on here with the logical operators?
This is to be expected.
In JavaScript (and many other languages), not only Booleans themselves are true or false, but other objects can be truthy or falsey as well (See the docs on mdn):
The value […] is converted to a boolean value, if necessary. If value is […] is 0, -0, null, false, NaN, undefined, or the empty string (""), [it is] false. All other values, including any object or the string "false", create […] true.
The logical operators || and && don't return true or false, rather they return the last argument to influence whether they are truthy or falsey (reference):
expr1 && expr2 – 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.
expr1 || expr2 – Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
The first step is to evaluate "abc" && 3.
false && 3 would return false,
true && 3 would return 3.
"abc" is not false, so JavaScript takes the second part, i.e. 3.
The second step is to evaluate 3 || "xyz". Here, JavaScript takes the first value which is not null, i.e. 3. This is similar to this.firstObject ?? this.defaultValue in C#: the second part is taken only when the first part is null.
the side effect is that you can do things like this:
x = x || {};
to set a variable to a default if it is not set.
Or
TrackingManager && TrackingManager.track("user was here")
to avoid bulkier if statements.