Given this snippet of JavaScript...
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = a || b || c || d || e;
alert(f); // 4
Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly?
My understanding is that variable f will be assigned the nearest value (from left to right) of the first variable that has a value that isn't either null or undefined, but I've not managed to find much reference material about this technique and have seen it used a lot.
Also, is this technique specific to JavaScript? I know doing something similar in PHP would result in f having a true boolean value, rather than the value of d itself.
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
This is made to assign a default value, in this case the value of y, if the x variable is falsy.
The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.
The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.
For example:
"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"
Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.
Javacript uses short-circuit evaluation for logical operators || and &&. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value.
The following values are considered falsy in JavaScript.
false
null
"" (empty string)
0
Nan
undefined
Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.
false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"
The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:
1 && [] && {} && true && "World" && null && 2010 // null
The first 5 values are all truthy and get evaluated until it meets the first falsy value (null) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.
The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.
var a = false;
var b = a || "Hello";
You could call the below example an exploitation of this feature, and I believe it makes code harder to read.
var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);
Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText, otherwise evaluate and return newMessagesText. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages.".
Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.
f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:
alert(null || undefined || false || '' || 0 || 4 || 'bar'); // alerts '4'
There isn't any magic to it. Boolean expressions like a || b || c || d are lazily evaluated. Interpeter looks for the value of a, it's undefined so it's false so it moves on, then it sees b which is null, which still gives false result so it moves on, then it sees c - same story. Finally it sees d and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.
This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).
This question has already received several good answers.
In summary, this technique is taking advantage of a feature of how the language is compiled. That is, JavaScript "short-circuits" the evaluation of Boolean operators and will return the value associated with either the first non-false variable value or whatever the last variable contains. See Anurag's explanation of those values that will evaluate to false.
Using this technique is not good practice for several reasons; however.
Code Readability: This is using Boolean operators, and if the behavior of how this compiles is not understood, then the expected result would be a Boolean value.
Stability: This is using a feature of how the language is compiled that is inconsistent across multiple languages, and due to this it is something that could potentially be targeted for change in the future.
Documented Features: There is an existing alternative that meets this need and is consistent across more languages. This would be the ternary operator:
() ? value 1: Value 2.
Using the ternary operator does require a little more typing, but it clearly distinguishes between the Boolean expression being evaluated and the value being assigned. In addition it can be chained, so the types of default assignments being performed above could be recreated.
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = ( a ) ? a :
( b ) ? b :
( c ) ? c :
( d ) ? d :
e;
alert(f); // 4
Return output first true value.
If all are false return last false value.
Example:-
null || undefined || false || 0 || 'apple' // Return apple
It's setting the new variable (z) to either the value of x if it's "truthy" (non-zero, a valid object/array/function/whatever it is) or y otherwise. It's a relatively common way of providing a default value in case x doesn't exist.
For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:
function doSomething(data, callback) {
callback = callback || function() {};
// do stuff with data
callback(); // callback will always exist
}
Its called Short circuit operator.
Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.
It could also be used to set a default value for function argument.`
function theSameOldFoo(name){
name = name || 'Bar' ;
console.log("My best friend's name is " + name);
}
theSameOldFoo(); // My best friend's name is Bar
theSameOldFoo('Bhaskar'); // My best friend's name is Bhaskar`
It means that if x is set, the value for z will be x, otherwise if y is set then its value will be set as the z's value.
it's the same as
if(x)
z = x;
else
z = y;
It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false is returned.
It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.
var x = '';
var y = 'bob';
var z = x || y;
alert(z);
Will output 'bob';
According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)
He also suggests another use for it (quoted):
"lightweight normalization of cross-browser differences"
// determine upon which element a Javascript event (e) occurred
var target = /*w3c*/ e.target || /*IE*/ e.srcElement;
Related
I know that in JavaScript you can do:
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...";
where the variable oneOrTheOther will take on the value of the first expression if it is not null, undefined, or false. In which case it gets assigned to the value of the second statement.
However, what does the variable oneOrTheOther get assigned to when we use the logical AND operator?
var oneOrTheOther = someOtherVar && "some string";
What would happen when someOtherVar is non-false?
What would happen when someOtherVar is false?
Just learning JavaScript and I'm curious as to what would happen with assignment in conjunction with the AND operator.
Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:
true && "foo"; // "foo"
NaN && "anything"; // NaN
0 && "anything"; // 0
Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty string, and of course false, anything else coerces to true.
&& is sometimes called a guard operator.
variable = indicator && value
it can be used to set the value only if the indicator is truthy.
Beginners Example
If you are trying to access "user.name" but then this happens:
Uncaught TypeError: Cannot read property 'name' of undefined
Fear not. You can use ES6 optional chaining on modern browsers today.
const username = user?.name;
See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Here's some deeper explanations on guard operators that may prove useful in understanding.
Before optional chaining was introduced, you would solve this using the && operator in an assignment or often called the guard operator since it "guards" from the undefined error happening.
Here are some examples you may find odd but keep reading as it is explained later.
var user = undefined;
var username = user && user.username;
// no error, "username" assigned value of "user" which is undefined
user = { username: 'Johnny' };
username = user && user.username;
// no error, "username" assigned 'Johnny'
user = { };
username = user && user.username;
// no error, "username" assigned value of "username" which is undefined
Explanation: In the guard operation, each term is evaluated left-to-right one at a time. If a value evaluated is falsy, evaluation stops and that value is then assigned. If the last item is reached, it is then assigned whether or not it is falsy.
falsy means it is any one of these values undefined, false, 0, null, NaN, '' and truthy just means NOT falsy.
Bonus: The OR Operator
The other useful strange assignment that is in practical use is the OR operator which is typically used for plugins like so:
this.myWidget = this.myWidget || (function() {
// define widget
})();
which will only assign the code portion if "this.myWidget" is falsy. This is handy because you can declare code anywhere and multiple times not caring if its been assigned or not previously, knowing it will only be assigned once since people using a plugin might accidentally declare your script tag src multiple times.
Explanation: Each value is evaluated from left-to-right, one at a time. If a value is truthy, it stops evaluation and assigns that value, otherwise, keeps going, if the last item is reached, it is assigned regardless if it is falsy or not.
Extra Credit: Combining && and || in an assignment
You now have ultimate power and can do very strange things such as this very odd example of using it in a palindrome.
function palindrome(s,i) {
return (i=i || 0) < 0 || i >= s.length >> 1 || s[i] == s[s.length - 1 - i] && isPalindrome(s,++i);
}
In depth explanation here: Palindrome check in Javascript
Happy coding.
Quoting Douglas Crockford1:
The && operator produces the value of its first operand if the first operand is falsy. Otherwise it produces the value of the second operand.
1 Douglas Crockford: JavaScript: The Good Parts - Page 16
According to Annotated ECMAScript 5.1 section 11.11:
In case of the Logical OR operator(||),
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.
In the given example,
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...move along";
The result would be the value of someOtherVar, if Boolean(someOtherVar) is true.(Please refer. Truthiness of an expression). If it is false the result would be "these are not the droids you are looking for...move along";
And In case of the Logical AND operator(&&),
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.
In the given example,
case 1: when Boolean(someOtherVar) is false: it returns the value of someOtherVar.
case 2: when Boolean(someOtherVar) is true: it returns "these are not the droids you are looking for...move along".
I see this differently then most answers, so I hope this helps someone.
To calculate an expression involving ||, you can stop evaluating the expression as soon as you find a term that is truthy. In that case, you have two pieces of knowledge, not just one:
Given the term that is truthy, the whole expression evaluates to true.
Knowing 1, you can terminate the evaluation and return the last evaluated term.
For instance, false || 5 || "hello" evaluates up until and including 5, which is truthy, so this expression evaluates to true and returns 5.
So the expression's value is what's used for an if-statement, but the last evaluated term is what is returned when assigning a variable.
Similarly, evaluating an expression with && involves terminating at the first term which is falsy. It then yields a value of false and it returns the last term which was evaluated. (Edit: actually, it returns the last evaluated term which wasn't falsy. If there are none of those, it returns the first.)
If you now read all examples in the above answers, everything makes perfect sense :)
(This is just my view on the matter, and my guess as to how this actually works. But it's unverified.)
I have been seeing && overused here at work for assignment statements. The concern is twofold:
1) The 'indicator' check is sometimes a function with overhead that developers don't account for.
2) It is easy for devs to just see it as a safety check and not consider they are assigning false to their var. I like them to have a type-safe attitude, so I have them change this:
var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex();
to this:
var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex() || 0;
so they get an integer as expected.
I know that in JavaScript you can do:
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...";
where the variable oneOrTheOther will take on the value of the first expression if it is not null, undefined, or false. In which case it gets assigned to the value of the second statement.
However, what does the variable oneOrTheOther get assigned to when we use the logical AND operator?
var oneOrTheOther = someOtherVar && "some string";
What would happen when someOtherVar is non-false?
What would happen when someOtherVar is false?
Just learning JavaScript and I'm curious as to what would happen with assignment in conjunction with the AND operator.
Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:
true && "foo"; // "foo"
NaN && "anything"; // NaN
0 && "anything"; // 0
Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty string, and of course false, anything else coerces to true.
&& is sometimes called a guard operator.
variable = indicator && value
it can be used to set the value only if the indicator is truthy.
Beginners Example
If you are trying to access "user.name" but then this happens:
Uncaught TypeError: Cannot read property 'name' of undefined
Fear not. You can use ES6 optional chaining on modern browsers today.
const username = user?.name;
See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Here's some deeper explanations on guard operators that may prove useful in understanding.
Before optional chaining was introduced, you would solve this using the && operator in an assignment or often called the guard operator since it "guards" from the undefined error happening.
Here are some examples you may find odd but keep reading as it is explained later.
var user = undefined;
var username = user && user.username;
// no error, "username" assigned value of "user" which is undefined
user = { username: 'Johnny' };
username = user && user.username;
// no error, "username" assigned 'Johnny'
user = { };
username = user && user.username;
// no error, "username" assigned value of "username" which is undefined
Explanation: In the guard operation, each term is evaluated left-to-right one at a time. If a value evaluated is falsy, evaluation stops and that value is then assigned. If the last item is reached, it is then assigned whether or not it is falsy.
falsy means it is any one of these values undefined, false, 0, null, NaN, '' and truthy just means NOT falsy.
Bonus: The OR Operator
The other useful strange assignment that is in practical use is the OR operator which is typically used for plugins like so:
this.myWidget = this.myWidget || (function() {
// define widget
})();
which will only assign the code portion if "this.myWidget" is falsy. This is handy because you can declare code anywhere and multiple times not caring if its been assigned or not previously, knowing it will only be assigned once since people using a plugin might accidentally declare your script tag src multiple times.
Explanation: Each value is evaluated from left-to-right, one at a time. If a value is truthy, it stops evaluation and assigns that value, otherwise, keeps going, if the last item is reached, it is assigned regardless if it is falsy or not.
Extra Credit: Combining && and || in an assignment
You now have ultimate power and can do very strange things such as this very odd example of using it in a palindrome.
function palindrome(s,i) {
return (i=i || 0) < 0 || i >= s.length >> 1 || s[i] == s[s.length - 1 - i] && isPalindrome(s,++i);
}
In depth explanation here: Palindrome check in Javascript
Happy coding.
Quoting Douglas Crockford1:
The && operator produces the value of its first operand if the first operand is falsy. Otherwise it produces the value of the second operand.
1 Douglas Crockford: JavaScript: The Good Parts - Page 16
According to Annotated ECMAScript 5.1 section 11.11:
In case of the Logical OR operator(||),
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.
In the given example,
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...move along";
The result would be the value of someOtherVar, if Boolean(someOtherVar) is true.(Please refer. Truthiness of an expression). If it is false the result would be "these are not the droids you are looking for...move along";
And In case of the Logical AND operator(&&),
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.
In the given example,
case 1: when Boolean(someOtherVar) is false: it returns the value of someOtherVar.
case 2: when Boolean(someOtherVar) is true: it returns "these are not the droids you are looking for...move along".
I see this differently then most answers, so I hope this helps someone.
To calculate an expression involving ||, you can stop evaluating the expression as soon as you find a term that is truthy. In that case, you have two pieces of knowledge, not just one:
Given the term that is truthy, the whole expression evaluates to true.
Knowing 1, you can terminate the evaluation and return the last evaluated term.
For instance, false || 5 || "hello" evaluates up until and including 5, which is truthy, so this expression evaluates to true and returns 5.
So the expression's value is what's used for an if-statement, but the last evaluated term is what is returned when assigning a variable.
Similarly, evaluating an expression with && involves terminating at the first term which is falsy. It then yields a value of false and it returns the last term which was evaluated. (Edit: actually, it returns the last evaluated term which wasn't falsy. If there are none of those, it returns the first.)
If you now read all examples in the above answers, everything makes perfect sense :)
(This is just my view on the matter, and my guess as to how this actually works. But it's unverified.)
I have been seeing && overused here at work for assignment statements. The concern is twofold:
1) The 'indicator' check is sometimes a function with overhead that developers don't account for.
2) It is easy for devs to just see it as a safety check and not consider they are assigning false to their var. I like them to have a type-safe attitude, so I have them change this:
var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex();
to this:
var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex() || 0;
so they get an integer as expected.
I don't get operation process of the below statement.
var x = x || {};
I think that what it does is
IF x exists, assign it to var x, if not assign null. "undefined || null?"
why do we need the later " || null " part?
A link to lessons or little help would be grrreat!
null and undefined don't enter into this anywhere.
All this does is set x to the value {} if x is a "falsy" value. {} is an empty object literal.
You probably know || and && as OR and AND in conditions. They work by "short circuit evaluation", meaning || will stop evaluating and return the last expression as soon as any of the expressions (starting from the very left) evaluates to true. (In other words: Since only one expression is required to be true for the whole compound to evaluate to true, we may stop as soon as any of them is true.) On the other hand && stops evaluating as soon as any of the expression is evaluating to false (so the whole compound can't be true as soon as any of its parts is false). In other words, && will continue evaluating the terms as long as they are true and || as long as the terms are false.
Now, we may not only use these operators in conditions, but anywhere in the code. For example a && b(); is equivalent to the if-clause if (a) b();. Similarly, || may be used for "is not": a || b(); is equivalent to if (!a) b();.
Since || returns the value of the first term from the left that evaluates to true, we may use this on the righthand-side in order to assign a default value (in case that the previous term(s) would evaluate to false):
a = b || c;
is equivalent to
if (b) {
a = b;
}
else {
a = c;
}
We may do this with any number of terms:
var api = window.webAPI || window.webkitWebAPI || window.mozWebAPI;
(This would evaluate to the hypothetical "window.webAPI", or, if undefined, look for the "webkitWebAPI" and then for the "mozWebAPI".)
In the case of var x = x || {}; the construct just makes sure that x is something (apparently something object-like), and if not, makes it an empty object ({}).
It is equivalent to the if-clause
var x;
if (!x) x = {};
So, why would we use this? Obviously, when first encountered, it initializes variable x to an empty object. But it does this conditionally: If x would have been set before, it preserves the value of x. Also, since we declare x as a variable in the same clause, we make sure that we do not hit an undeclared identifier (saving an extra declaration on another line).
This question already exists:
Closed 12 years ago.
Possible Duplicate:
In Javascript, what does it mean when there is a logical operator in a variable declaration?
Stumbled across this code online, have no idea what it does, wasn't able to find out with FireBug either, and I can't google it because of the special characters...
var myValue = myInput.value || 0;
if myInput.value is undefined (or another falsy value) then the default value of 0 will be set
some examples...
myInput.value = undefined
var myValue = myInput.value || 0;
// myValue = 0
myInput.value = 10
var myValue = myInput.value || 0;
// myValue = 10
|| is often called the default operator. It lets you give a default value, if something else is falsy. So if myInput.value is undefined, for example, myValue will be assigned 0.
Because of the way the javascript interpreter is built, it can interpret certain classes of values or even the existence (or non-existence) of values as true or false
undefined, null, false, 0, empty string, NaN can be interpreted as false
the existence of a non-false value can be interpreted as not-false, thus in many cases, true; Don't confuse not-false with true though. They are sometimes loosely interpreted as the same, but not-false contains everything that isn't interpreted as false, whereas true is much more specific.
Thus:
if (myMethod)
myMethod();
Can be used to check for the existence of myMethod before running it.
The || symbol is a short-circuiting OR statement. If the first part of the OR is or can be interpreted as not-false, then that part of the statement will preside and the value will be taken and used as myValue. If javascript deems that the first part of the statement is interpreted as false, then the second part of the OR will be returned.
Thus in the statement:
var myValue = myInput.value || 0;
myValue will become whatever myInput.value contains if it contains anything that javascript can interpret as not false. Thus it could contain "Hi, hell of a day we've got here!" and that would be returned to myValue.
When I say not-false, I don't strictly mean true, because "Hi, hell of a day we've got here" isn't [strictly speaking] interpreted as true, but is "coerced" to being interpreted that way.
If myInput.value doesn't contain anything that javascript could coerce to being interpreted as true, then 0 will be returned to myValue.
So in this case, if myInput.value is undefined, null, false, 0 etc. then myValue = 0
It's a way of having a default value of 0 in case myInput.value is null (undefined)
Javascript has a defined left to right evaluation order. So if you write something like
if (method() || method2()) { ... }
method2() will never happen if method() returns true, because true OR anything will always be true.
This works the same for the example you are giving in Javascript.
If "myinput.value" evaluates to something trueish, this value will be assigned, otherwise 0 will be assigned for every falsish value (null, 0, "").
It sets myValue to the value of myInput or to 0, if the myInput value is anything that’s considered false in JavaScript (especially undefined or null). The trick is the short-circuit behaviour of the || operator. When you evaluate a||b and a is true, the || operator returns a:
console.log('a'||'b'); // 'a'
When the first argument is false, the || operator returns its second argument:
console.log(undefined||'b'); // 'b'
It’s also good to ponder this:
var foo = 0;
console.log('a'||foo++);
console.log(foo); // 0
console.log(undefined||foo++); // 0
console.log(foo); // 1
The || operator in many langiages includes an optimization called short-cutting: if the left side evaluates to a true value then the right side does not need to be evaluated. True || anything == true. This is often used to provide default values, as in your example code. If the left hand side myInput.value evaluates to true, then the whole expression will return that value. Otherwise, the whole expression will return the right hand value of 0.
Note that this also depends on the || operator returning the original values rather than a boolean true or false value. Each side is evaluated to true or false for the logic test, but not for the expression's return value.
function or(a, b) {
if (a) { return a; }
return b;
}
MyValue will be equal to myInput.value OR 0 if the previous value can be regarded as False.
Value can be regarded as False is its empty string (''), zero (0) etc. Anything that say True in this code myInput.value == False
It means that if myInput.value isn't defined, myValue will be set to 0. Think || same as OR.
Given this snippet of JavaScript...
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = a || b || c || d || e;
alert(f); // 4
Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly?
My understanding is that variable f will be assigned the nearest value (from left to right) of the first variable that has a value that isn't either null or undefined, but I've not managed to find much reference material about this technique and have seen it used a lot.
Also, is this technique specific to JavaScript? I know doing something similar in PHP would result in f having a true boolean value, rather than the value of d itself.
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
This is made to assign a default value, in this case the value of y, if the x variable is falsy.
The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.
The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.
For example:
"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"
Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.
Javacript uses short-circuit evaluation for logical operators || and &&. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value.
The following values are considered falsy in JavaScript.
false
null
"" (empty string)
0
Nan
undefined
Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.
false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"
The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:
1 && [] && {} && true && "World" && null && 2010 // null
The first 5 values are all truthy and get evaluated until it meets the first falsy value (null) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.
The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.
var a = false;
var b = a || "Hello";
You could call the below example an exploitation of this feature, and I believe it makes code harder to read.
var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);
Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText, otherwise evaluate and return newMessagesText. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages.".
Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.
f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:
alert(null || undefined || false || '' || 0 || 4 || 'bar'); // alerts '4'
There isn't any magic to it. Boolean expressions like a || b || c || d are lazily evaluated. Interpeter looks for the value of a, it's undefined so it's false so it moves on, then it sees b which is null, which still gives false result so it moves on, then it sees c - same story. Finally it sees d and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.
This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).
This question has already received several good answers.
In summary, this technique is taking advantage of a feature of how the language is compiled. That is, JavaScript "short-circuits" the evaluation of Boolean operators and will return the value associated with either the first non-false variable value or whatever the last variable contains. See Anurag's explanation of those values that will evaluate to false.
Using this technique is not good practice for several reasons; however.
Code Readability: This is using Boolean operators, and if the behavior of how this compiles is not understood, then the expected result would be a Boolean value.
Stability: This is using a feature of how the language is compiled that is inconsistent across multiple languages, and due to this it is something that could potentially be targeted for change in the future.
Documented Features: There is an existing alternative that meets this need and is consistent across more languages. This would be the ternary operator:
() ? value 1: Value 2.
Using the ternary operator does require a little more typing, but it clearly distinguishes between the Boolean expression being evaluated and the value being assigned. In addition it can be chained, so the types of default assignments being performed above could be recreated.
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = ( a ) ? a :
( b ) ? b :
( c ) ? c :
( d ) ? d :
e;
alert(f); // 4
Return output first true value.
If all are false return last false value.
Example:-
null || undefined || false || 0 || 'apple' // Return apple
It's setting the new variable (z) to either the value of x if it's "truthy" (non-zero, a valid object/array/function/whatever it is) or y otherwise. It's a relatively common way of providing a default value in case x doesn't exist.
For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:
function doSomething(data, callback) {
callback = callback || function() {};
// do stuff with data
callback(); // callback will always exist
}
Its called Short circuit operator.
Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.
It could also be used to set a default value for function argument.`
function theSameOldFoo(name){
name = name || 'Bar' ;
console.log("My best friend's name is " + name);
}
theSameOldFoo(); // My best friend's name is Bar
theSameOldFoo('Bhaskar'); // My best friend's name is Bhaskar`
It means that if x is set, the value for z will be x, otherwise if y is set then its value will be set as the z's value.
it's the same as
if(x)
z = x;
else
z = y;
It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false is returned.
It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.
var x = '';
var y = 'bob';
var z = x || y;
alert(z);
Will output 'bob';
According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)
He also suggests another use for it (quoted):
"lightweight normalization of cross-browser differences"
// determine upon which element a Javascript event (e) occurred
var target = /*w3c*/ e.target || /*IE*/ e.srcElement;