In the book 'Functional javascript' by Michael Fogus, I faced with one expression that I still can't undrestand.
Here is the function:
function defaults(d){
return function(o, k){
var val = fnull(_.identity, d[k]);
return o && val(o[k]);
}
}
where
function fnull(fun /*, defaults*/){
var defaults = _.rest(arguments);
return function(/* args */){
var args = _.map(arguments, function(e, i){
return existy(e)?e : defaults[i];
});
return fun.apply(null, args);
};
};
function existy(x){return x != null}
(underscore is the object of Underscore.js library)
and the example of use:
function doSomething(config){
var lookup = defaults({critical:108});
return lookup(config, 'critical');
}
doSomething({critical: 9});
//=> 9
doSomething({});
//=> 108
I've recreated exapmle in node.js and it works fine, but I wonder why is the logical 'and' in the return line of 'default' function?
return o && val(o[k]);
What is the point of doing that? I checked the exapmle with
return val(o[k]);
and it also worked well.
It's hard to believe that this is just a mistake...
The logical and will make sure the second part is only evaluated if the first part is true. If o does not evaluate to true, the expression returns false. Otherwise, it returns val(o[k]).
This is used as a quick check to see if o is not false / null / undefined.
return o && val(o[k])
mean that if "o" is TRUE it will return "val(o[k])"
given "expr1 && expr2":
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
That is smart usage of something called short "short-circuiting" in logical expressions.
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.
The rules of logic guarantee that these evaluations are always correct. Note that the (anything) part of the above expressions is not evaluated (meaning not ran at all), so any side effects of doing so do not take effect. There are also benefits to it.
Usage:
Make your expressions evaluate faster by putting something easily calculable or likely to be true/fail at leftmost position in expression.
For example parOfExpressionLikelyToBeTrue && (rest of expression) will in most cases not even calculate the other part of expression. Same goes for parOfExpressionLikelyToBeTrue || (rest of espression).
Same can be used if something is very time consuming to calculate, you push it as far back to the right in expression. For example (rest of the expression) && ThisCostsALotOfTime or (rest of the expression) || ThisCostsALotOfTime. Here when first parts of expression short-circuit you save time on your time consuming part.
Short circuit existence evaluation. Lets say you need to check if your object's property pr is 3? What would you do? obj.pr === 3? Yes and no. What if property is missing? It's fine you will get undefined and that is not === 3. But what if object is not there. You will get trying to read pr of undefined error. You can use short-circuit logic here to you benefit by being defensive and writing the expression as if (obj || obj.pr === 3). This ensures there are no errors, only true and false.
Short circuit initialization. Let's say you wanna say variable a is b. But b might be undefined. And you wanna your variable to have a default. You could write a=b and then check if a is undefined and set it to default or you can be clever and write it as a = b || 3. This way a is b or if be is undefined it's 3. Ofc, you can use this for late initialization as well a = a || 3.
Making sure object for function exists before trying to run function. Same as before mentioned with properties you might wanna test if object containing the function exists before running the function. Let's say you got object obj and function fn as it's property. You might call that function like obj.fn(). It's fine, but if obj is undefined you will get an error. Being defensive you might wanna write: obj && obj.fn().
Running the function only if there is one. Since functions in JS can be passed to other functions you can not be sure at run time it's there. Being defensive you might wanna run your function as (typeof passedFunction === "function" && passedFunction() instead just passedFunction() which my produce an error.
other smart things like guardian expressions etc which are complicated and too many to for me to remember all and you should avoid them anyway for better code readability.
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.
This question already has answers here:
Javascript: || instead of IF statement - is this legal and cross browser valid?
(10 answers)
Closed 6 years ago.
So I'm reading Airbnb's JS styleguide and I don't understand what the OR operator is doing in the following example. More specifically in the Jedy constructor options || (options = {}); Is basically creating an empty object if no arguments were passed to the constructor? Therefore, the name property of the Jedi constructor would be set to 'no name'?
function Jedi(options) {
options || (options = {});
this.name = options.name || 'no name';
}
Jedi.prototype.getName = function getName() {
return this.name;
};
Jedi.prototype.toString = function toString() {
return 'Jedi - ' + this.getName();
};
PS. It seems like there are a lot shorthand ways of doing things with JS. Are there any good resources or articles explaining what these are and when it's best to use them?
The || operator takes two arguments. If the first argument is a "truthy" value, it returns the first argument; otherwise, it returns the second. It also short-circuits; that is, if the first argument is truthy it does not evaluate the second. If the second argument is an expression with side effects, this can be very significant.
The statement options || (options = {}); relies on this. If options is truthy, then the assignment expression will not be evaluated. If it is falsy, then the second expression will be evaluated.
Now, this is functional equivalent to the statement options = options || {};. In theory, that statement could be slightly slower, because it will assign options to itself rather than simply not assigning anything. However, the effect of this is negligible.
Js logical operators return not true or false, but truly or falsy value itself. For example in expression x && y, if x is falsy, then it will be returned, otherwise y will be returned. So the truth table for operator is correct.
The same for ||. It's a good way for specifying function default values.
You will often find this code in JavaScript plugins it basically means if an object with name options does not exists create a new one
If you try to access a property on options like
options.name and options does not exists then it will give you an error that options is undefined.But with this options || (options = {}) code you can always ensure that the JavaScript Object you are accessing always exists.
I will check if I could provide you some links for this to read about.
This is a good supporting link
How can I create an empty namespace object without overwriting another object with the same name?
seems like this is a more concise way of checking that the object exists and assigning it the value of an empty object if it does not. It isn't all that clear though. A little clearer implementation would be
var options = options || {};
even better, use es2015 default parameters
function Jedi(options = {}) {
this.name = options.name || 'no name';
}
In many (most) programming languages, at runtime unnecessary executions are optimized away. ||binary operator returns true if either of its operands evaluate to true. Since both the operands are serially evaluated, if the first one evaluates to true, the outcome of || operator is going to be true. so the second operand need not be evaluated. If the first one returns false, then second one decides what the result of || operator is going to be. this is the behavior that is being exploited here.
if options is set to non null value, it will evaluate to true. So don't execute the second operand which initializes it to empty object. on the next line if options.name is not null, then initialize it to 'no name'
What is the meaning of && in this JavaScript code?
function doIt(a) {
var b = a.parents(),
c = 1;
return b.each(function() {
jQuery(this).hasClass("free-content") && (c = 0)
}), c
}
normally I would think this would be a logical operator AND, but I can't figure out what it does in this line.
The logical AND operator in this case is used in place of an IF-statement. It will set c to 0 if jQuery(this).hasClass("free-content") returns a truthy value.
It's equivalent to:
if (jQuery(this).hasClass("free-content")) {
c = 0;
}
You wondering what it means is actually the reason I dislike this type of coding and consider it a bad practice. It's hard to read and can create confusion, which in turn can create bugs.
It's also worth noting what logical AND returns, if you want to use the returned value:
(Logical AND) 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.
Here's an example showing, in my opinion, bad code since it's hard to follow:
var foo = bar && baz || qux;
The above code is equivalent to:
var foo;
if (bar && baz) {
foo = baz;
} else {
foo = qux;
}
Summary: Do not use logical operators as a nifty way to replace IF-statements or to save keystrokes. It will most likely come back and bite you or someone else in the ass.
I know there will be people arguing against me on this (usually the same people who doesn't want to use semicolon because ASI), but it's just a really bad idea to write code that only an expert would understand. There's no argument against it.
return b.each(function () {
jQuery(this).hasClass("free-content") && (c = 0)
}), c
b.each loops over all entries in b, and checks whether the current element has the class free-content set. Only if that yields true, the second part of the expression is evaluated – because they are concatenated via &&, and JavaScript stops evaluating such an expression when the first part is false, because then the whole expression can’t become true any more.
So if there is an element with that class, the second part is evaluated – and thereby c is set to the value 0 (because that’s the assignment operator = there, and not a comparison).
And after that each loop is finished, the value of c is returned to the outside – because each() and c are connected via the comma operator , here, which evaluates its operands from left to right and then “returns” the second one.
JavaScript allows a lot of “fancy” coding like this, but as Marcus already said in his answer, that is hard to read, and there is no actual advantage here over, say
b.each(function() {
if(jQuery(this).hasClass("free-content")) {
c = 0;
return false;
}
});
return c;
I added the return false here inside the each loop, because once we found an element with that class, we don’t need to search the rest of them any more – that’s something that the person who came up with the original code forgot to do in all their “fancy-ness” … their loop will continue to iterate over all of b’s elements, not matter if it finds the element it is looking for in the first round already.
I have an object that contains a string HelloWorld in the attribute hello. I want to check for two strings, and if it does not match with either one, then I want to execute certain code.
var item = { hello: "HelloWorld" }
item.hello !== "HelloWorld" && item.hello !== "GoodbyeWorld" // false, correct
However, I feel this can be optimized and made more readable:
item.hello !== ("GoodbyeWorld" && "HelloWorld") // false, correct
item.hello !== ("HelloWorld" && "GoodbyeWorld") // true WTF?
I expected both checks to be falsy, but surely I'm missing something here. I think I do not have a correct understanding of the AND/OR operator in javascript, or I am using the parenthesis in a wrong manner. Can anyone explain?
JSFiddle example
The result of "HelloWorld" && "GoodbyeWorld" is "GoodbyeWorld" which is why you're getting the result you are, the previous way you were doing it is the simplest solution
Let's take a look at this line
item.hello !== ("HelloWorld" && "GoodbyeWorld") // true WTF?
The logical AND operator evaluates its right operand, if lVal is a truthy value.
Note, a truthy value is every value which is not falsy (null,false,0,"",undefined,NaN)
Since "HelloWorld" is indeed truthy
The expression ("HelloWorld" && "GoodbyeWorld") evaluates to "GoodbyeWorld" and you're effectively comparing
item.hello !== "GoodbyeWorld" which can be reduced to "HelloWorld" !== "GoodbyWorld"
Hence, is true
However, if you're on an ES5 compatible environment you could use Array.prototype.indexOf to simplify it.
!~["HelloWorld","GoodbyWorld"].indexOf(item.hello) //false
the above returns true if item.hello is not contained in the array
No, you can't optimise the expression that way. What you are doing is elliminating one of the strings, so that you are only doing one of the comparisons.
The && operator uses short circuit evaluation, which means that if the first operand is truthy, it will just return the second operand.
So, what your code is doing is to compare the hello property value to the second one of the strings, which explains the results that you get.
item.hello !== "HelloWorld" && item.hello !== "GoodbyeWorld"
is the proper way to test whether item.hello is distinct from "HelloWorld" and "GoodbyeWorld".
An expression A && B in JavaScript yields a result which is either A or B and it's that result, that is compared to your item.hello.
I saw this construction in order to get the browser viewport width:
function () { return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; }
I understand the browser quirks involved. What I don't understand is why || returns the value. So I tried this alert(undefined || 0 || 3); and sure enough, it alerts 3. I find this bizarre, because I expect true or false. Could anyone explain what's going on?
The JavaScript operator || is defined to return the left value if it evaluates to a truthy value, otherwise the right value instead of returning true itself. That's just how it's defined in the spec.
I know it can be annoying at times, you might accidentally end up holding a reference to something you don't want to hold on to, but it also allows for the handy trick your example has. Everything has its pros and cons.
Take a look at the ECMAScript standards section 11.11 Binary Logical Operators
The production LogicalORExpression :
LogicalORExpression ||
LogicalANDExpression is evaluated as
follows:
1.Evaluate LogicalORExpression.
2.Call GetValue(Result(1)).
3.Call ToBoolean(Result(2)).
4.If Result(3) is true, return Result(2).
5.Evaluate LogicalANDExpression.
6.Call GetValue(Result(5)).
7.Return Result(6).
So it evaluates the boolean conversion of each operand, but returns the actual value of the operand.
If you want to know how Javascript converts values to a boolean, see section 9.2 ToBoolean
Don't think of it as "or". It's more like a flow-control device within an expression. The value of a || expression is the value of the first subexpression that's "truthy". Thus, the evaluation of the series of subexpressions stops at some point, as if
expr1 || expr2 || expr3
were
(function() {
var rv = expr1;
if (rv) return rv;
rv = expr2;
if (rv) return rv;
return expr3;
})()
The OR function is a short-circuit OR evaluation - it returns the first element that is not false, or the last false element otherwise.
This is actually quite useful, so you can write expressions like
a = a || someValue;
Which is the same as
if (a==null)
a = someValue;
It's just the way it is by design. ||, like && is a short-circuit operator, the expressions are evaluated in order, they stop after an expression meets the criteria and yield the result of the expression. The same is true of &&:
var myObj = { "Test": { "Foo":"Bar" } };
var myObj2 = { "Foo": "Bar" };
alert(myObj.Test && myObj.Test.Foo); // will alert "Bar";
alert(myObj2.Test && myObj2.Test.Foo); // will alert undefined;
Some values, such as zero, "" or undefined, are treated as false. Anything else is true, so the || operator just returns the first non-zero (ie true) value in the pair that it's given. This is useful for tricks like the code above, but I'm guessing it wasn't added to the language just to let you skip the odd if statement.
I suspect it may have originated as a performance tweak, since the higher-level languages (such as BASIC ... yes, maybe an odd definition of higher-level) used fixed constants for true and false -- often 0 and -1, or 0 and 1.