This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Closed 8 years ago.
edit :
Quote removed. is not related to the question.
Question
How come does it always (when all are truthy) takes the last value ?
Examples :
f= 1 && 2 && 3 //3
f= 'k' && 'd' && 's' //'s'
p.s. : I've noticed that when investigating the pub/sub using $.callbacks
Operator && acts as an if-statement. The short-circuit occurs only if a value is false. Otherwise, it keeps evaluating statements.
When you write a && b it means: a ? b : a.
Similarly, a || b means: a ? a : b.
Edit: author has clarified the question significantly.
JavaScript logical AND operator return the left operand if it is falsy or else it returns the right operand.
Let us take a look at the table of logical truth:
A B A && B
true true true
true false false
false true false
false false false
As you can see, if A is false, we can return it:
A A && B
false false
false false
If A is not false, we can return B:
B A && B
true true
false false
This is a minor optimization, which leads to interesting sideeffects when used with weak typing, such as inline if:
var result = callback && callback()
// Generally equivalent to a simple if:
if (callback)
result = callback();
else
result = null;
Also using default options:
name = name || 'John';
// Generally equivalent to a simple if:
if (!name)
name = 'John';
As to why it happens, well, because these operators are defined like that in ECMA-262.
So how come does it always (when all are truthy) takes the last value ?
Because it can't short-circuit if the leading values are truthy, because it's an "AND" operator, and all operands must be truthy to satisfy the condition.
Re your comment below:
yes but why does it returns the last value ?
Because it's useful. :-) In the very first version of JavaScript from Netscape, it just returned true if the overall expression was true and false if not, but almost immediately they realized that it's much more useful if it returns the final operand.
For instance, you can do this:
var value = obj && obj.value;
...which will set value to be either a falsey value (if obj is falsey) or obj.value (if obj is not falsey). Importantly, it won't throw an error if obj is falsey. Very handy for guarding if you don't know for sure that obj is set. You don't have to stop at one level, either:
var value = obj && obj.sub && obj.sub.value;
value will either be falsey, or the value of obj.sub.value if both obj and obj.sub are truthy (e.g., because we seem to be using them as objects, they're object instances rather than null or undefined).
|| does the same sort of thing: It returns its first truthy operand.
More: JavaScript's Curiously Powerful OR Operator (||)
Because if first one is truthy, then it should go on and check second operand till the last one. If you would go with 1 || 2 || 3 instead it will return 1.
&& is a logical operator. This tests whether a value is truthy or falsy. This linked article explains that falsy values are equal to undefined, null, NaN, 0, "" and false.
Logical expressions are checked from left to right. If any part of the expression is evaluated t be falsy, the remainder of the expression will not be evaluated. In your examples, the value is always truthy. Here we can break down your first expression:
f = 1 && 2 && 3;
f = 1 /* Okay, 1 is a truthy value, lets continue... */
f = 2 /* Still truthy, let's continue... */
f = 3 /* Still truthy, we've reached the end of the expression, f = 3. */
If any of the values before 3 were falsy, the expression would have ended. To show this in action, simply redeclare your variable as:
f = 1 && 2 && 0 && 3;
Here 0 is a falsy value (as mentioned above). The execution of your expression here will end at 0:
f = 1 /* Okay, 1 is a truthy value, lets continue... */
f = 2 /* Still truthy, let's continue... */
f = 0 /* Hey, this is falsy, lets stop here, f = 0. */
f = 3 /* We never get here as the expression has ended */
Here f ends up being 0.
In your jQuery.Topic() example, && is used to ensure that id actually exists:
topic = id && topics[id]
We can break this down in the same way:
/* Assume this is your topics array: */
topics = ["", "My First Topic", "My Second Topic"];
/* If we pass in the value 1 as "jQuery.Topic(1)": */
topic = id && topics[id]
topic = 1 /* This is truthy, let's continue... */
topic = topics[1] /* topics[1] === "My First Topic" */
/* Now lets assume we pass in nothing as "jQuery.Topic()": */
topic = id && topics[id]
topic = null /* This is falsy, let's stop here, topic = null. */
The following if statement will only work if topic is truthy. In the first example, this is the case as topic has a value which is set to a string which isn't empty. In the second example, topic is null which is falsy.
The ECMAScript Standard states 12.11.2 Runtime Semantics: Evaluation:
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
1. Let lref be the result of evaluating LogicalANDExpression.
2. Let lval be GetValue(lref).
3. Let lbool be ToBoolean(lval).
4. ReturnIfAbrupt(lbool).
5. If lbool is false, return lval.
6. Let rref be the result of evaluating BitwiseORExpression.
7. Return GetValue(rref).
That is, first we check whether the first operand is evaluated to be a "falsy" value (null, false, 0). If it is, then the first operand is returned.
If, however, it's "thruthy", then the same process is repeated for the second operand and if it is evaluated as a truthy value, then the original value is returned (7. Return GetValue(rref)).
Short-circuit evaluation and returning the second expression instead of a bool are quite useful features.
The && operator evaluates the left operand and if it's truthy evaluates the right operand. Similarly the || operator evaluates the left operand and if it's falsy evaluates the right operand.
This allows to write things like
draw_element(color || "#F00");
with the meaning of using color unless if it's not specified (e.g. color is null, undefined or "") and in that case the default value is used.
You can even use things like
draw_element(color || pick_new_color());
and the function pick_new_color() will be called only if a color is not specified.
A very common use of && instead is to avoid errors, e.g:
if (x && x.constructor == Array) {
...
}
because if x is null or undefined you cannot access attributes (an exception would be raised if you try). The fact that && returns the first result if it's falsy instead of just false is not so useful indeed. Your code example does it, but it's not something you will find often in Javascript programs.
To recap: && and || are short-circuiting (i.e. they don't even evaluate the second operand if the result is known after evaluating the first) and this is very useful. They also return the falsy/truthy value itself instead of a bool, and this is very useful for || (not so much useful for &&).
Related
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;
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 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.