JavaScript OR (||) variable assignment explanation
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
What's the difference between ( ' ' || false) and (false || ' ' ) in JavaScript?
See in the same page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR
expr1 || expr2
If
expr1
can be converted totrue
, returnsexpr1
; else, returnsexpr2
.
Javascript || operator behavior
Take a look in operator precedence: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
"x" || "y" == "y"
is "x"
and it is truthy (Understanding JavaScript Truthy and Falsy), so ... ? ... : ...
returns first expression
The logical && and || operators in JavaScript
So what exactly is happening when you use the
&&
and||
operators with chaining values
&&
is a binary operator, with one left-hand operand and one right-hand operand. The expression a && b && c && d && e
is parsed based on associativity rules so that it looks like this:
if (a && (b && (c && (d && e)))) {
Based on the semantics of &&
, if a
is falsy, the entire condition immediately evaluates to a
, which is falsy. If a
is truthy, then the expression evaluates to the right side, which is b && (c && (d && e)))
. In that case if b
is falsy, then that sub-expression, and thus the entire expression, immediately evaluates to b
, which is falsy; if b
is truthy, then that sub-expression evaluates to its right side, which is c && (d && e)
, and the process continues.
The net result is the intuitive behavior that for the entire expression to be falsy, and therefore for the if
branch to not be taken, it suffices for any of the variables to be falsy. The evaluation will "short-circuit"--resulting in falsy--as soon as any falsy variable is encountered. For the entire expression to be truthy, and therefore for the if
branch to be taken, all the variables must be truthy.
For ||
, the logic is reversed. For the entire expression to be truthy, and therefore for the if
branch to be taken, it suffices for any of the variables to be truthy. The evaluation will "short-circuit"--resulting in truthy--as soon as the first truthy value is encountered. For the entire expression to be falsy, and therefore for the if
branch not to be taken, all the variables must be falsy.
You Don't Know JS has a good explanation too.
Javascript Logical OR operator in return statement of a function
(title) => !!title || "Title is required"]
This line is saying:
Iftitle
is present, returntrue
, otherwise return"Title is required"
.
Let's break it down...
To start with, the arrow function is just shorthand for:
function xxxx (title) {
return !!title || "Title is required"];
}
Next, the !!
is a double negation, effectively just the logical not opperator twice. The first negation converts the data (whatever it data type it may be) to a boolean. The second negation changes the boolean again to give the desired result.
E.g. !!'hello'
--> true
, !!0
--> false
, !!undefined
--> false
The next part is a comparison. The ||
is OR opperator, so if the first half is true / present, then it will be returned, if not, the part after the ||
will be returned.
E.g. true || 'some text'
will return true
, wheras false || 'some text'
will return some text
Here are some example, try running the snippet to see the outputs
const checkTitle = (title) => !!title || "Title is required"
// 1. No parameters, should print "Title is required"
console.log('Test 1', checkTitle());
// 2. Parameter presentbut empty, should print "Title is required"
console.log('Test 2', checkTitle(""));
// 3. Title present, and valid, should preint 'true'
console.log('Test 3', checkTitle('Hello World!'));
When should I use ?? (nullish coalescing) vs || (logical OR)?
The OR operator ||
uses the right value if left is falsy, while the nullish coalescing operator ??
uses the right value if left is null
or undefined
.
These operators are often used to provide a default value if the first one is missing.
But the OR operator ||
can be problematic if your left value might contain ""
or 0
or false
(because these are falsy values):
console.log(12 || "not found") // 12
console.log(0 || "not found") // "not found"
console.log("jane" || "not found") // "jane"
console.log("" || "not found") // "not found"
console.log(true || "not found") // true
console.log(false || "not found") // "not found"
console.log(undefined || "not found") // "not found"
console.log(null || "not found") // "not found"
In many cases, you might only want the right value if left is null
or undefined
. That's what the nullish coalescing operator ??
is for:
console.log(12 ?? "not found") // 12
console.log(0 ?? "not found") // 0
console.log("jane" ?? "not found") // "jane"
console.log("" ?? "not found") // ""
console.log(true ?? "not found") // true
console.log(false ?? "not found") // false
console.log(undefined ?? "not found") // "not found"
console.log(null ?? "not found") // "not found"
While the ??
operator isn't available in current LTS versions of Node (v10 and v12), you can use it with some versions of TypeScript or Node:
The ??
operator was added to TypeScript 3.7 back in November 2019.
And more recently, the ??
operator was included in ES2020, which is supported by Node 14 (released in April 2020).
When the nullish coalescing operator ??
is supported, I typically use it instead of the OR operator ||
(unless there's a good reason not to).
Difference between || and ?? operators
The main difference is that nullish coalescing(??)
operator will only give the result as the right operand only if the left operand is either null
or undefined
.
Whereas the OR(||)
operator will give the result as right operand for all the falsy values of the left operand.
Below are some examples
- Snippet 1: With
0
as input
const a = 0;
// a || 10 --> Will result in 10, as || operator considers 0 as falsy value and resulting the right side operand
console.log(`a || 10 = ${a || 10}`);
// a ?? 10 --> Will result in 0, as ?? operator considers 0 as truthy value and resulting the left side operand
console.log(`a ?? 10 = ${a ?? 10}`);
Related Topics
Ckeditor: Class or Id for Editor Body
Restart a Gif Animation Without Reloading the File
Why Does Reflow Need to Be Triggered for CSS Transitions
Get All Computed Style of an Element
Extract the Current Dom and Print It as a String, with Styles Intact
Change Svg Fill Color in :Before or :After CSS
How to Dynamically Remove a Stylesheet from the Current Page
Converting Em to Px in JavaScript (And Getting Default Font Size)
Creating a CSS Class in Jquery
Jquery-Ui Datepicker Change Z-Index
Detecting by How Much User Has Scrolled
Chrome 65 Blocks Cross-Origin <A Download>. Client-Side Workaround to Force Download
Why Do We Need to Use Radix Parameter When Calling Parseint
Find All Possible Subset Combos in an Array
Why Does JavaScript Variable Declaration at Console Results in "Undefined" Being Printed