Meaning of || in javascript argument [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does “options = options || {}” mean in Javascript?
What is the meaning of the || in the second argument?
var obj = this;
var settings = $.extend({
param: 'defaultValue'
}, options || {});
Also would be nice if anyone knows how to search that character("|") here or in google! Thank you

That would be the logical OR. The statement will return the first truth-y value it finds.
In this case, if options is null (or any other value that isn't truth-y) it will evaluate to false. The || will then return the empty object.

That is some kind of fallback value or default value. So if the object is null or false the second value is used.

More importantly in that scenario, if options is not defined then an empty object {} is passed as an argument. Its kind of a side-effect use case of the logical OR operator. More specifically, it uses short circuiting. For example in the below case
a || b
if a is true then b never gets executed, but if a is false then b gets executed. Hence in the example you have shown, if options is not defined and thus false, then {} gets executed and thus passed as a parameter.

|| = or
As in the comparison operator.

|| = "OR". Example:
alert(false || false || false || "I'm valid!"); // alerts "I'm valid"
In your question, the example above demonstrates that the function requires an object for it's options. In this case, if the local variable "options" is not available, then just pass an empty object. Later, in the function that's being called, it's probably setting default values in that new object.

Related

Logical OR with a variable and a function definition as operands [duplicate]

This question already has answers here:
What does the construct x = x || y mean?
(12 answers)
Closed 6 years ago.
I saw this line when I was reading a custom library created by a third party developers. What does this do in Javascript? Does it perform Logical OR on "modifier" and a return value from the function?
modifier = modifier || function( x ){ return x; };
Yes.
More in detail, it checks if modifier evaluates to true; in this case it assigns modifier value to modifier variable (noop); otherwise it assigns an anonymous function to modifier.
It returns modifier, if it has a truthy value, like function. Otherwise it returns a function without calling it.
Yes. In JavaScript, the || returns the left if it is a truthy value or the right if the left is a falsy value.
Effectively, if modifier is already a function, it will just leave it set. If it is undefined or null, it will set a reference to the right side function. It will not evaluate the function, however.
It would look like this if evaluated.
modifier = modifier || function( x ){ return x; }(); // notice the method invocation
The || operator is a lazy one. If it has the means necessary to compute it's value it doesn't evaluate the rest of the expression. The value of the logical operation OR is true when one of the parameters is true, so if modifier is considered to be a true value it will return itself and when not it returns the second parameter.
To see what is considered true in JS check here.

What is the meaning of these statements || {} in this javascript code [duplicate]

This question already has answers here:
What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?
(8 answers)
Closed 7 years ago.
I'm just getting going in javascript and am reading up on the module pattern.
I have been looking at this page: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html and cannot work out what the || {} statements mean.
There are quite a few places where this code is written: (UTIL || {}));
Can anyone explain what these statements mean and what they are doing?
I assume that || means OR - but am not too certain in this context.
Here is the code from the conclusion of the article. The second and the penultimate lines are examples of the code that has me puzzled.
var UTIL = (function (parent, $) {
var my = parent.ajax = parent.ajax || {};
my.get = function (url, params, callback) {
// ok, so I'm cheating a bit :)
return $.getJSON(url, params, callback);
};
// etc...
return parent;
}(UTIL || {}, jQuery));
This is used to define a variable if it is not set.
You can do this to ensure there is a value set!
for example:
function iHaveParameters(param1, param2) {
param1 = param1 || {} //empty object
param2 = param2 || "This should be a string"
}
And of course as noted, it will only invoke the second value when the first variable is null.
And in your case it is actually only setting the variable when it's not set, meaning if you include the script 3000 times, the variable will only still be defined once avoiding CPU. This way you could require the loading of a function for example
As has been said, it's an empty JavaScript object.
What's not so obvious I guess is why you would do that. A common reason is to make your code safe if the object happens to be null or undefined. Consider the example where you are passed an object and want to access an attribute of it:
function myFunc(obj) {
console.log(obj.name);
}
That's fine, unless obj is undefined, in which case your code will crash.
A safer way is often:
function myFunc(obj) {
console.log((obj || {}).name);
}
Now if obj is undefined then a new empty object is created instead. Getting the .name of that is safe and will simply return undefined.
This is obviously an over-simplified example, but the technique is widely used to make code shorter and easier to read (less tests and branches than putting if statements everywhere).
It means: if the object before || is null, use a new empty object {} instead.
Read more about the operator here: Is there a "null coalescing" operator in JavaScript?
{} is a short way of declaring an empty object, the same way as using [] do declare an empty array.
var my = parent.ajax = parent.ajax || {}; means that if the object parent.ajax exist then set it as the value. If not, set an empty object instead.

use of OR in javascript object in my case confusion [duplicate]

This question already has answers here:
Javascript || operator
(5 answers)
Closed 8 years ago.
Question 1
What does options.left = options.left || _KSM.drawOption.left means? I know _KSM.drawOption is referring to the object (also a function), but how does the || operator work here? Does it mean if _KMS.drawOption.left is undefinded, assign options.left to options.left?
Question 2
Why the author didn't use this keyword in this case? I assume it's because in this demo he didn't create an instance, because he just do the calling once. Rigtht? (I've seen a lots of this in jquery plugin that's why I'm consufed when the author call the function name instead of this within a function)
Question 1
This is a way to set a default value to a variable. It actually evaluate the left side and if it is falsy, the variable will be equal to the right side (even if it is also falsy).
That is a bad way of assigning default variable especially when working with integer. 0 is considered as falsy, so you will never be able to assign 0 as a left property. Instead, it will always be the default parameter of _KMS.drawOption .
Question 2
We don't have the full code so we can only assume. But my assumption would be that draw is an event, a function bind with addEventListener. That mean the context (this value) is the target of the event. My guess would be a canvas.
Logical Operators in JavaScript work a bit differently than most people expect.
Logical OR (||)
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.
So instead of the expression resulting in a boolean value, it returns the first value that isn't "falsey". This has the benefit of being a great way to fill in default values in case it is undefined, null, 0, or an empty string.
var myObj = { name: 'Josh' };
myObj.age = myObj.age || 33;
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.
Basically just the opposite. Since any expression that evaluates to false will short circuit the logical check, it can be useful to test for the existence of a field, before trying to use it.
var myObj = null;
if(myObj && myObj.person && myObj.person.name === "Josh") // false, no error
var myObj = {};
if(myObj && myObj.person && myObj.person.name === "Josh") // false, no error
var myObj = {person: {}};
if(myObj && myObj.person && myObj.person.name === "Josh") // false, no error
var myObj = {person: {name: "Josh"}};
if(myObj && myObj.person && myObj.person.name === "Josh") // true
However! Caution should be taken here because in the case of both boolean values true or false and integer values 0 or anything not 0 you might end up overwriting a legitimate value.
Question 2: Not enough context

javascript object assignment expression - comparison

Suppose we've got an optional parameter of a function which can come as undefined. Is there any difference between
options || (options = {});
and
options = options || {};
? If there is none, which one do you find better (I mean faster or more readable)? The question is - which one would you use to implement optional parameters in javascript?
Those exact 2 lines are different :
in the first one its an expression which do nothing with options ( if it is not defined) while the other is a statement.
Logically, they both are the same.
options || (options = {});
If options is a Truthy value, then it will short circuit and will not go to the next part. If it is a Falsy value, it goes to the next part where and empty object is created and assigned to options.
options = options || {};
The same thing, first right hand side is evaluated. If options is Truthy, it will be assigned as it is to options, if it is Falsy, an empty object is created and that is assigned to options.
Note: If options is an optional parameter of a function, and if it can accept other Falsy values, even if the user passes a Falsy value, intentionally, like false, 0, null, it will still use an empty object

What does the Javascript expression 'a = a || function() {...}' mean?

I'm not sure what this construct means but I've seen it a few times. The example below is from another Stack Overflow question. I'm not sure how to interpret the initial "or" construct itself:
Object.keys = Object.keys || (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
DontEnums = [
'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
],
DontEnumsLength = DontEnums.length;
//etc...
});
a = a || function(){...} is an idiom that is very common in Javascript. It relies on two concepts that, while not unique to Javascript, you might not yet be familiar with.
1. Operator short circuiting
Operator short circuiting[wikipedia] is a compiler optimization that was invented to prevent unnecessary evaluation.
To demonstrate this, let us suppose that we want to determine whether a person is a teenager: that is, whether a person has an age inclusively between 13 and 19 years.
var isTeenager = person.age >= 13 && person.age <= 19;
Now, let us suppose that the code executes and it turns out that the person is younger than 13. The first condition will be evaluated and will return false. Since the program now knows that the the left hand side of the && operator is false, and since && requires both sides to be true in order to evaluate to true, it knows that evaluating the right hand side is pointless.
In other words, the program, having seen that the person's age is not greater than 13, already knows that he is not a teenager and couldn't care less whether or not he is less than 19.
The same sort of principle applies to the || operator. Suppose we wanted to know if a person can ride the bus for free: that is, if the person is over 70 years old or is handicapped.
var canRideFree = person.age >= 70 || isHandicapped(person);
If the person is over 70, the program already knows that he can ride free. At this point, the program does not care if he is handicapped or not and thus does not evaluate the call to the isHandicapped function. If, on the other hand, the person was younger than 70, then canRideFree would be set to whatever isHandicapped returns.
2. Truthy and falsy values
Truthy and falsy values[some random person's blog] are the boolean evaluations of objects. In Javascript, every object will evaluate to either a "truthy" or a "falsy" value.
An expression is "falsy" if its value is any of these:
false, null, undefined, 0, "", NaN
Everything else is truthy.
People take advantage of the fact that a null or undefined variable evaluates to false. This means that you can check if a variable exists very easily:
if (a) { /* a exists and is not a falsy value */ }
Combining what we know
The || operator short circuits and returns the value of the last expression that it evaluates. This principle combines with truthiness in this single statement:
Object.keys = Object.keys || function() {...}
If Object.keys is truthy, it will be evaluated and assigned to itself. Otherwise, Object.keys will be assigned to the function. This is a very common idiom in Javascript for checking if a value already exists and assigning it to something else if it doesn't.
Some other languages, such as C#, that do not have truthiness, have a null-coalescing operator[MSDN] that has a similar purpose.
object Value = PossiblyNullValue ?? ValueIfNull;
In this code, Value will be assigned to PossiblyNullValue, unless it's null, in which case it will be assigned to ValueIfNull.
tl;dr [wikipedia]
If you didn't bother to read anything I said above, all you need to know is that a = a || function() {...} basically does what this code does:
if (exists(Object.keys)) {
Object.keys = Object.keys;
} else {
Object.keys = function() {...};
}
function exists(obj) {
return typeof obj !== "undefined" &&
obj !== null &&
obj !== false &&
obj !== 0 &&
obj !== "" &&
!isNaN(obj);
}
This looks incomplete to me, but it seems as if it is a shim for Object.keys. Basically, if the property doesn't exist (in non standards compliant browsers, for example), we implement it ourselves.
The or operator will evaluate the second operand only if the first one is falsy. As such
alert(false || "Hello, world");
Will alert "Hello, world". In this case, Object.keys would be undefined, which evaluates to false.
The || basically means: If Object.keys is not defined, define it using the expression behind the ||.
This behavior bases on the JavaScript feature that any variable that is undefined evaluates to false. If the variable is true, the second expression does not need to be evaluated, if it is false it does.
From what I can tell, that code attempts to define the function Object.keys if it isn't already defined (or if it's false). The function to the left of || will become the function Object.keys.
The reason I said "from what I can tell" is that you haven't posted the entire code snippet. Notice that the code after || reads (function(){ instead of just function(){. It's possible that the author has set up the function to be self invoking.
If, after the function definition, you see })(), then the return value of the function is stored in Object.keys. If not, then the function itself is stored there.

Categories

Resources