var connections = {key: 1234}
var thisconnection = connections["key"] || {status:"new"};`
In the above code, the variable thisconnection is subjected to the Logical operator '||'
When I simply type the following code in the console, thisconnection takes the value of the connections["key"] in any case.
Why don't you try it?
var connections = {key: 1234};
var thisconnection = connections["key"] || {status:"new"};
console.log(thisconnection); // returns 1234
Explanation:
If connections.key returned 0, NaN, false, undefined, "" (empty string), or any value that evaluated to false, it would continue evaluating the next || expression.
However, if the expression evaluates to a truthy value, the whole statement is finished with evaluation. This is known as short-circuiting:
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
false && (anything) is short-circuit evaluated to false.
true || (anything) is short-circuit evaluated to true.
Since 1234 is a truthy value, evaluation stops and the value 1234 is assigned.
In the following statement
var thisconnection = connections["key"] || {status:"new"};
You are saying if connection["key"] exists assign connection["key"] to thisconnection, other wise assign {status:new} to thisconnection.
It's same as following code
if(connections["key"]){
thisconnection = connection["key"]
}
else{
thisconnection = {status:new}
}
if connections["key"] is nil then {status:"new"} will be the value of variable
In JavaScript, || and && operators have a specific behavior when used in variable assignment. If you have something like this:
var theResult = a || b || c || d;
Then, the variable theResult won't be a boolean as we expect in other languages.
If a is truhty, then theResult = a. Else, if b is truhty, then theResult = b. And so on... If all variables are falsy, then theResult = d because d is the last statement in the or condition.
The rule is the following:
the value of theResult will be the value of the variable in a || b || c || d which break the chain
So, since we have only OR conditions, then the first value which resolve to true will break the chain. I mean, if a === true, then it's not needed to evaluate the rest of the condition because true || false || whatEver || weDontCare will always be true. If none of the variable breaks the chain, then the last variable is assigned to theResult.
First it will check connections["key"],
If it is not null, then the value of thisconnection with contain value of connections["key"]. Otherwise thisconnection will contain value of {status:"new"}.
Related
Related to Is there a "null coalescing" operator in JavaScript? - JavaScript now has a ?? operator which I see is in use more frequently. Previously most JavaScript code used ||.
let userAge = null
// These values will be the same.
let age1 = userAge || 21
let age2 = userAge ?? 21
In what circumstances will ?? and || behave differently?
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).
In short
The Nullish Coalescing Operator ?? distinguishes between:
nullish values (null, undefined)
falsey but defined values (false, 0, '' etc.)
|| (logical OR) treats both of these the same.
I created a simple graphic to illustrate the relationship of nullish and falsey values in JavaScript:
Further explanation:
let x, y
x = 0
y = x || 'default' // y = 'default'
y = x ?? 'default' // y = 0
As seen above, the difference between the operators ?? and || is that one is checking for nullish values and one is checking for falsey values. However, there are many instances where they behave the same. That is because in JavaScript every nullish value is also falsey (but not every falsey value is nullish).
Using what we learned above we can create a few examples for different behavior:
let y
y = false || 'default' // y = 'default'
y = false ?? 'default' // y = false
y = 0n || 'default' // y = 'default'
y = 0n ?? 'default' // y = 0n
y = NaN || 'default' // y = 'default'
y = NaN ?? 'default' // y = NaN
y = '' || 'default' // y = 'default'
y = '' ?? 'default' // y = ''
Since the new Nullish Coalescing Operator can differentiate between no value and a falsey value, it can be beneficial if you, for example, need to check if there is no String or an empty String. Generally, you probably want to use ?? instead of || most of the time.
Last and also least here are the two instances where they behave the same:
let y
y = null || 'default' // y = 'default'
y = null ?? 'default' // y = 'default'
y = undefined || 'default' // y = 'default'
y = undefined ?? 'default' // y = 'default'
As a very short rule, you could look at it the opposite way:
|| (or) returns the first "truthy" value (or the last value if no "truthy" value exists)
?? (nullish coalescing) returns the first "defined" value (or the last value if no "defined" value exists)
Example
x = false || true; // --> true (the first 'truthy' value - parameter 2)
x = false ?? true; // --> false (the first 'defined' value - parameter 1)
As described in the MDN:
Contrary to the logical OR (||) operator, the left operand is returned if it is a falsy value which is not null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). See below for more examples.
And also in the answer to the question you linked:
Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:
alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)
Base on MDN docs:
Contrary to the logical OR (||) operator, the left operand is returned if it is a falsy value which is not null or undefined.
Conceptual Example:
When use || for a falsy value that is NOT undefined or null:
false || 'name'; // ==> the 'name' is returned
But when using ?? for above case:
false ?? 'name'; // ==> the false is returned
Real Example:
Assume, we have a phone variable that is not mandatory in our form and the empty string ('') is valid for us and we wanna doSomething() if the phone variable is null or undefined, now guess what:
When use || for a falsy value that is NOT undefined or null:
const phone = ''; // assume it became empty string from some action
phone || doSomething(); // ==> damn, the doSomething is run
// but we want to run it if it's `undefined` or `null` the empty string is valid for us
But when using ?? for above case:
const phone = ''; // same assumption like above
phone ?? doSomething(); // ==> yeah, that's right
// the empty string is valid for us and the doSomething is not run
Note: actually it is an example and in a real project you can have a better sense of this lovely operation usage.
Attention: for the undefined or null both of them act like each other.
function f(input) {
const val = input || 1;
return 41 + val;
}
function g(input) {
const val = input ?? 1;
return 41 + val;
}
console.log("using ||:", f(0));
console.log("using ??:", g(0));
The null(ish) coalescing operator only works with null and undefined. So, use the null(ish) coalescing operator when you don't want those values but you will otherwise accept other falsy values:
console.log(null ?? "nullish");
console.log(undefined ?? "nullish");
console.log("" ?? "nullish");
console.log(0 ?? "nullish");
console.log(false ?? "nullish");
The logical OR will skip over any falsy value and give you the other thing.
The logical OR will skip over any falsy value and give you the other parameter. This does work and is by now idiomatic, however it is not always what you want:
console.log(null || "falsy");
console.log(undefined || "falsy");
console.log("" || "falsy");
console.log(0 || "falsy");
console.log(false || "falsy");
Here are few rules for how to determine which one you need. The simplest tests:
do you only want to protect against null (and undefined - it's usually the same thing)? Then use ??. If you aren't sure, it's probably a good idea to default to the nullish coalescing operator.
do you know you also don't want 0 or "", for example? Then use ||.
The second one is where it actually gets trickly. How do you know you need to discard falsy values? Well, the very first snippet shows what happens if you do that: f(0) will discard the zero and thus produce a different result. This is a somewhat common source of bugs. Since the construct a = b || c is common to introduce a fallback value (in this case c) it might accidentally fall back to it when you didn't mean to.
function updateAge(years) {
var yearsToAdd = years || 1;
return this.age + yearsToAdd
}
This works if you want to provide a fallback for calling updateAge() (no argument) but fails if you call updateAge(0) (no update). Similarly, you could have:
function sayMyName(greeting) {
var prefix = greeting || "Hello, my name is ";
return prefix + this.firstName;
}
Again, this works for sayMyName() (no argument) but fails for sayMyName("") (explicitly no greeting).
To generalise, if you are providing a fallback value that's different to the falsy value, then you might have a problem. However, if your fallback is the falsy value - num || 0 or str || "" then it doesn't really matter.
It's rare (or should be) that you might expect a mixed type (number, or string, or object, etc) and provide a fallback to it: input || fallback is valid but will reject empty strings and zeroes. It's usually going to be wrong unless you explicitly don't want any of those.
To put it simply, you should likely use the nullish coalescing operator ?? at all times. It will be less cognitive load to figure out whether it's a potential bug or not. There is also not much reason to avoid it. It's newer than the boolean OR, so it doesn't work on older environments, that's true, however nowadays you should likely be transpiling your code for those. If you cannot or prefer not to, then you don't have a choice and should use the boolean OR.
When the || is being used as a boolean conditional that goes to false. For example:
let userAge = false
// These values will be the same.
let age1 = userAge || 21 // 21
let age2 = userAge ?? 21 // false
The logical OR will still give the next value for anything that doesn't evaluate to true. So it gives the value 21 in this case. Where ?? only handles null and undefined.
In short, when you care that let a variable assigned from a possible null undefined source, and you wish to provide a default value to the variable, use the nullish coalescing operator ??.
If you want to avoid messing yourself around with the JavaScript definition of falsy truthy [1], then don't use ||.
nullish coalescing operator ??
JavaScript definition of falsy
a real example in angular
/* parse the url pattern
/search?keyword=mykeyword&page=3
/search?keyword=mykeyword
*/
ngOnInit(): void {
const keyword = this.route.snapshot.queryParamMap.get('keyword') ?? 'default keyword';
const page = this.route.snapshot.queryParamMap.get('page') ?? '0';
this.queryResult$ = this.service.getQueryResult(keyword, +page);
this.keyword = keyword;
}
[1]:
Each programming language has its own definition of falsy truthy. The basic approach to tell whether a value is a truthy value is that if the explicit type conversion function bool(value) results in true, then the value is truthy.
For those might work across languages, PHP and C# also have ??. See PHP, C#.
When I run this code the code in the if- block gets executed. My assumption was that if ! something, it's either null or undefinded? Can anyone explain?
const num = 0;
if (!num) {
console.log('Why on earth does this get printed');
}
Your assumption is incorrect. When you implicitly convert a value to a boolean like that, it's converted according to the truthy and falsy rules. The falsy values are 0, "", NaN, null, undefined, and of course, false. (Also, interestingly, document.all on browsers.) All other values are truthy. So if (!num) will be true if num is 0, because you've negated a falsy value (making it true).
If you just want to check for null and undefined, you can use == undefined or num == null (note: ==, not ===), which is true for both of them:
if (num == null) {
console.log("num is null or undefined");
}
The rules for == are such that both null and undefined are == undefined (and also == null), but nothing else is.
Or, perhaps more clearly:
if (num === null || num === undefined)
console.log("num is null or undefined");
}
When you are using if statement, code in curly braces executes only if expression in round braces return true.
You variable num has 0 assigned to it.
Variable num would be converted to false because 0 is assigned to it
In Javascript, the exclamation mark (“!”) symbol, called a “bang,” is the logical “not” operator. Placed in front of a boolean value it will reverse the value, returning the opposite.
Because of that you will get true inside curly braces
This is a reason why your code executes
Related to Is there a "null coalescing" operator in JavaScript? - JavaScript now has a ?? operator which I see is in use more frequently. Previously most JavaScript code used ||.
let userAge = null
// These values will be the same.
let age1 = userAge || 21
let age2 = userAge ?? 21
In what circumstances will ?? and || behave differently?
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).
In short
The Nullish Coalescing Operator ?? distinguishes between:
nullish values (null, undefined)
falsey but defined values (false, 0, '' etc.)
|| (logical OR) treats both of these the same.
I created a simple graphic to illustrate the relationship of nullish and falsey values in JavaScript:
Further explanation:
let x, y
x = 0
y = x || 'default' // y = 'default'
y = x ?? 'default' // y = 0
As seen above, the difference between the operators ?? and || is that one is checking for nullish values and one is checking for falsey values. However, there are many instances where they behave the same. That is because in JavaScript every nullish value is also falsey (but not every falsey value is nullish).
Using what we learned above we can create a few examples for different behavior:
let y
y = false || 'default' // y = 'default'
y = false ?? 'default' // y = false
y = 0n || 'default' // y = 'default'
y = 0n ?? 'default' // y = 0n
y = NaN || 'default' // y = 'default'
y = NaN ?? 'default' // y = NaN
y = '' || 'default' // y = 'default'
y = '' ?? 'default' // y = ''
Since the new Nullish Coalescing Operator can differentiate between no value and a falsey value, it can be beneficial if you, for example, need to check if there is no String or an empty String. Generally, you probably want to use ?? instead of || most of the time.
Last and also least here are the two instances where they behave the same:
let y
y = null || 'default' // y = 'default'
y = null ?? 'default' // y = 'default'
y = undefined || 'default' // y = 'default'
y = undefined ?? 'default' // y = 'default'
As a very short rule, you could look at it the opposite way:
|| (or) returns the first "truthy" value (or the last value if no "truthy" value exists)
?? (nullish coalescing) returns the first "defined" value (or the last value if no "defined" value exists)
Example
x = false || true; // --> true (the first 'truthy' value - parameter 2)
x = false ?? true; // --> false (the first 'defined' value - parameter 1)
As described in the MDN:
Contrary to the logical OR (||) operator, the left operand is returned if it is a falsy value which is not null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). See below for more examples.
And also in the answer to the question you linked:
Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:
alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)
Base on MDN docs:
Contrary to the logical OR (||) operator, the left operand is returned if it is a falsy value which is not null or undefined.
Conceptual Example:
When use || for a falsy value that is NOT undefined or null:
false || 'name'; // ==> the 'name' is returned
But when using ?? for above case:
false ?? 'name'; // ==> the false is returned
Real Example:
Assume, we have a phone variable that is not mandatory in our form and the empty string ('') is valid for us and we wanna doSomething() if the phone variable is null or undefined, now guess what:
When use || for a falsy value that is NOT undefined or null:
const phone = ''; // assume it became empty string from some action
phone || doSomething(); // ==> damn, the doSomething is run
// but we want to run it if it's `undefined` or `null` the empty string is valid for us
But when using ?? for above case:
const phone = ''; // same assumption like above
phone ?? doSomething(); // ==> yeah, that's right
// the empty string is valid for us and the doSomething is not run
Note: actually it is an example and in a real project you can have a better sense of this lovely operation usage.
Attention: for the undefined or null both of them act like each other.
function f(input) {
const val = input || 1;
return 41 + val;
}
function g(input) {
const val = input ?? 1;
return 41 + val;
}
console.log("using ||:", f(0));
console.log("using ??:", g(0));
The null(ish) coalescing operator only works with null and undefined. So, use the null(ish) coalescing operator when you don't want those values but you will otherwise accept other falsy values:
console.log(null ?? "nullish");
console.log(undefined ?? "nullish");
console.log("" ?? "nullish");
console.log(0 ?? "nullish");
console.log(false ?? "nullish");
The logical OR will skip over any falsy value and give you the other thing.
The logical OR will skip over any falsy value and give you the other parameter. This does work and is by now idiomatic, however it is not always what you want:
console.log(null || "falsy");
console.log(undefined || "falsy");
console.log("" || "falsy");
console.log(0 || "falsy");
console.log(false || "falsy");
Here are few rules for how to determine which one you need. The simplest tests:
do you only want to protect against null (and undefined - it's usually the same thing)? Then use ??. If you aren't sure, it's probably a good idea to default to the nullish coalescing operator.
do you know you also don't want 0 or "", for example? Then use ||.
The second one is where it actually gets trickly. How do you know you need to discard falsy values? Well, the very first snippet shows what happens if you do that: f(0) will discard the zero and thus produce a different result. This is a somewhat common source of bugs. Since the construct a = b || c is common to introduce a fallback value (in this case c) it might accidentally fall back to it when you didn't mean to.
function updateAge(years) {
var yearsToAdd = years || 1;
return this.age + yearsToAdd
}
This works if you want to provide a fallback for calling updateAge() (no argument) but fails if you call updateAge(0) (no update). Similarly, you could have:
function sayMyName(greeting) {
var prefix = greeting || "Hello, my name is ";
return prefix + this.firstName;
}
Again, this works for sayMyName() (no argument) but fails for sayMyName("") (explicitly no greeting).
To generalise, if you are providing a fallback value that's different to the falsy value, then you might have a problem. However, if your fallback is the falsy value - num || 0 or str || "" then it doesn't really matter.
It's rare (or should be) that you might expect a mixed type (number, or string, or object, etc) and provide a fallback to it: input || fallback is valid but will reject empty strings and zeroes. It's usually going to be wrong unless you explicitly don't want any of those.
To put it simply, you should likely use the nullish coalescing operator ?? at all times. It will be less cognitive load to figure out whether it's a potential bug or not. There is also not much reason to avoid it. It's newer than the boolean OR, so it doesn't work on older environments, that's true, however nowadays you should likely be transpiling your code for those. If you cannot or prefer not to, then you don't have a choice and should use the boolean OR.
When the || is being used as a boolean conditional that goes to false. For example:
let userAge = false
// These values will be the same.
let age1 = userAge || 21 // 21
let age2 = userAge ?? 21 // false
The logical OR will still give the next value for anything that doesn't evaluate to true. So it gives the value 21 in this case. Where ?? only handles null and undefined.
In short, when you care that let a variable assigned from a possible null undefined source, and you wish to provide a default value to the variable, use the nullish coalescing operator ??.
If you want to avoid messing yourself around with the JavaScript definition of falsy truthy [1], then don't use ||.
nullish coalescing operator ??
JavaScript definition of falsy
a real example in angular
/* parse the url pattern
/search?keyword=mykeyword&page=3
/search?keyword=mykeyword
*/
ngOnInit(): void {
const keyword = this.route.snapshot.queryParamMap.get('keyword') ?? 'default keyword';
const page = this.route.snapshot.queryParamMap.get('page') ?? '0';
this.queryResult$ = this.service.getQueryResult(keyword, +page);
this.keyword = keyword;
}
[1]:
Each programming language has its own definition of falsy truthy. The basic approach to tell whether a value is a truthy value is that if the explicit type conversion function bool(value) results in true, then the value is truthy.
For those might work across languages, PHP and C# also have ??. See PHP, C#.
I am confused about the below if statement code. Not sure what it is exactly doing
if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
Can someone please help me to understand this?
Is it a short-circuiting in if statement:
i.e
1- if first this.props.filterURL from left side is false then it will return false. 2- if first this.props.filterURL has a value then it will return true and the second variable nextProps.filterURL will be compared to this.props.filterURL on the right most of the statement?
Notes :
This short-circuiting is good for the performance, as it allows significant bits of calculations to be skipped.
The AND operator (&&) returns true if both expressions are true, otherwise it returns false.
DEMO
var x = 1;
var y = 5;
if (x > 0 && y < 6) { console.log(x) }; // true
if(x > 1 && y < 6) { console.log(x) }; // false
As suggested by nnnnnn in his comment, the first this.props.filterURL is checking for a truthy value, not for true specifically. If the property is not defined that is falsy, but if the value is null or 0 or an empty string those are all falsy too.
In case of AND operator it evaluates the second expression only if the first one is true.
In your case,
if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
can be interpreted as if(expr1 && expr2)
where expr1= this.props.filterURL and expr2 = nextProps.filterURL !== this.props.filterURL
for first expression expr1 it evaluates whether it is not null or undefined...
for the second expression expr2 nextProps.filterURL !== this.props.filterURL it checks both the value and data type. So for example if you have both value as same 1234 but for one it is of type String and for another it is for number, this condition would be true.
In javascript, if we have some code such as
var a = "one";
var b = q || a;
alert (b);
The logical OR operator will assign a's value to b, and the alert will be "one."
Is this limited to assignments only or can we use it everywhere?
It seems an empty string is treated the same as undefined. Is this right?
How does this work with AND variables? What about combinations of them?
What is a good example of when to use these idioms, or when not to?
For your q || a to evaluate to a, q should be a 'falsy' value. What you did is called "Short circuit evaluation".
Answering your questions:
The logical operators (like and - &&, or - ||) can be used in other situations too. More generally in conditional statements like if. More here
Empty string is not treated as undefined. Both are falsy values. There are a few more falsy values. More here
AND, or && in JavaScript, is not a variable. It is an operator
The idiom you have used is quite common.
var x = val || 'default'; //is generally a replacement for
var x = val ? val : 'default' //or
if (val)
var x = val;
else
var x = 'default';
The way || works in Javascript is:
If the left operand evaluates as true, return the left operand
Otherwise, return the right operand
&& works similarly.
You can make use of this for in-line existence checks, for example:
var foo = (obj && obj.property)
will set foo to obj.property if obj is defined and "truthy".
I'm not quite sure I follow your question. You can use an expression anywhere you can use an expression, and a logical operator on two expressions results in an expression.
alert(q||a);
alert(true||false);
var x=5;
var y=0;
if (y!=0 && x/y>2) { /*do something*/ }
The last bit is useful. Like most languages, Javascript 'short-circuits' ANDs and ORs. If the first part of an AND is false, it doesn't evaluate the second bit - saving you a divide-by-0. If the first part of an OR is true, it doesn't evaluate the second.
But you can use boolean operators anywhere you can use an expression.
Javascript evaluates logic by truethness/falseness. Values such as (false, "", null, undefined, 0, -0) are evaluated as logic false.
Combine this with the lazy evaluation, 'OR' operations are now evaluated from left to right and stops once true is found. Since, in your example, the truthness is not literally a boolean, the value is returned.
In this case:
x = 0; y = 5; alert(y || x)/*returns 5*/; alert(x || y)/*also returns 5*/;
this can also be other objects.
functionThatReturnsTrue() || functionThatDoesSomething();
This behavior is shared with other scripting languages like Perl. The logical OR operator can be used as a syntactic shorthand for specifying default values due to the fact that the logical OR operator stops evaluating its operands when it encounters the first expression that evaluates to true: "evaluate the first operand and if the value is interpreted as not false, assign it. Otherwise repeat for the second operand."
I find I often use this behavior to specify default values for function parameters. E.g.
function myFunction(foo, bar) {
var fooValue = foo || "a";
// no need to test fooValue -- it's guaranteed to be defined at this point
}
IMHO - don't use for boolean type assignment. It can be confusing. As undefined !== false, ie false itself is a value.
E.g. If u want to copy a field value from an object if and only if that field is defined
var bar.value = false;
var foo = true;
var foo = bar.value || foo; // ==> should be false as bar.value is defined
For boolean type assignment, u should really use
var foo = (bar.value !== undefined) ? bar.value : foo;