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.
Related
I'm currently learning and educating myself on javascript, i just found one simple code which is using this '()();' what is this called, didnt find much information about it, what is it and how it is used, here the code i found :
'use strict';
let obj, method;
obj = {
go: function() { alert(this); }
};
obj.go();
(obj.go)();
(method = obj.go)();
(obj.go || obj.stop)();
sory english is not my mother language if some mistake.
Used on their own, parenthesis are grouping operators. They group expressions to control the order or precedence of the evaluation. You can read MDN here about it.
// example // is the same as
(obj.go)(); obj.go();
(method = obj.go)(); method = obj.go; method();
(obj.go || obj.stop)(); // calling go or stop after assinging to a temp variable
That piece of code is demonstrating how this is bound within a function execution content (in this case in go). It shows that simply putting parentheses around a method does not alter that behaviour: this is still bound to obj.
As soon as the parentheses surround an expression involving operator(s) the situation changes, and the method that results from the expression is called without a specific this binding: the default applies (undefined).
Another variant is the following:
(0,obj.go)();
Here the comma-operator kicks in, and so we are in the expression case: this is no longer bound to obj in the method call.
It just controls the order of the execution. You could write everything like this too, to make it more clear:
// (obj.go)();
obj.go();
// (method = obj.go)();
method = obj.go;
method();
// (obj.go || obj.stop)();
var method = obj.go || obj.stop;
method();
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does “var FOO = FOO || {}” mean in Javascript?
I am finding this kind of statement in javascript object creation repeatedly.
var MyObj = MyObj || {};
Could some one could explain the significance of the above statement?
why can't we create just
var MyObj = {};
Thanks.
var MyObj = MyObj || {};
That simply says "if MyObj already exists and has a truthy value, keep it; otherwise, create a new object". It's a common way of doing optional parameters to functions, for example.
See MDN's page on logical operators for more information on the subject.
What if MyObj already exists.
If it alreay exists .. the statement
var MyObj = {} resets the object (which is bad)
Hence it is usually done with ||
If it already exists, preserve whatever it is ... else create a new object.
The || operator says:
this || that -> this OR that
So in your example
myObj is myObj or new Object if myObj isn't defined or set to falsy value (null, 0, "", false, undefined)
That means that if MyObj is evaluated to false (i.e. it is null or undefined) then create a new object. It is a short form that leverage the fact that if MyObj is evaluated to true when casted to boolean (i.e. it is not null and defined) the second part of the OR expression is not evaluated.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why is there a null value in JavaScript?
I don't understand what null is for. 'Undefined' as well.
It helps to appreciate the difference between a value and a variable.
A variable is a storage location that contains a value.
null means that the storage location does not contain anything (but null itself is just a special kind of value). Read that last sentence carefully. There is a difference between what null is and what null means. 99% of the time you only care about what null means.
Undefined means that the variable (as opposed to the value) does not exist.
null is an object you can use when creating variables when you don't have a value yet:
var myVal = null;
When you do this, you can also use it to check to see if it's defined:
// null is a falsy value
if(!myVal) {
myVal = 'some value';
}
I wouldn't use it this way, normally. It's simple enough to use 'undefined', instead:
var myVal; // this is undefined
And it still works as a falsy value.
Creating Objects
When you create an object in javascript, I like to declare all my object properties at the top of my object function:
function myObject() {
// declare public object properties
this.myProp = null;
this.myProp2 = null;
this.init = function() {
// ... instantiate all object properties
};
this.init();
}
I do this because it's easier to see what the object properties are right off the bat.
If a variable is not known or not initialized in the current scope it is undefined.
If you want to use a variable and indicate that it has an invalid value for instance you may want to assign it null because accessing an undefined variable will throw an error if you try to work with it (despite checking if it is undefined).
If something is undefined you also have the possibility to add it to an object. If a variable is defined but contains null you know that this variable may be used already by another part of your program.
For example, it can prepare a global variable to be used in more parts of the code.
If you start your code with var iNeedThisEverywhere = null; then you can use it inside more objects/actions in the code, but if you don't do that, then this variable will not be shared throughout the code.
Of course, you will actually put something inside that variable somewhere during the code, but since you defined this variable at the very beginning, it will be shared further anyway.
A variable holding null holds a reference to the "black hole" named null.
10 + 10 + null = null
Null is related historically to databases, http://en.wikipedia.org/wiki/Null_(SQL)
(Correct me if I'm wrong here)
A variable not initiated (unknown) is undefined.
regards,
/t
Sometimes I'll see code like this:
var Obj = Obj || {};
What does this do? I have had success writing
array = array || [];
To instantiate an array if it hasn't already been instantiated, however I would like to know a bit more about the mechanics of this.
The technique tries to make use of something called short circuit evaluation... but it's tricky in Javascript, and turns out to be quite dangerous if you try to make use of it for Object instantiation.
The theory behind short circuit evaluation is that an OR statement is only evaluated up to the first true value. So the second half of an OR statement is not evaluated if the first half is true. This applies to Javascript......
But, the peculiarities of Javascript, in particular how undeclared variables are handled, make this a technique that has to be used with great care to instantiate objects.
The following code creates an empty object except if Obj was previously declared in the same scope:
var Obj = Obj || {}; // Obj will now be {}, unless Obj was previously defined
// in this scope function.... that's not very useful...
This is because after var Obj, Obj will be undefined unless it was declared in the same scope (including being declared as a parameter to the function, if any).... so {} will be evaluated. (Link to an explanation of var provided in the comments by T.J. Crowder).
The following code creates an empty object only if Obj has been previously declared and is now falsy:
Obj = Obj || {}; // Better make sure Obj has been previously declared.
If the above line is used when Obj has not been previously declared, there will be a runtime error, and the script will stop!
For example this Javascript will not evaluate at all:
(function() {
Obj = Obj || "no Obj"; // error since Obj is undeclared JS cannot read from
alert(Obj); // an undeclared variable. (declared variables CAN
})(); // be undefined.... for example "var Obj;" creates
// a declared but undefined variable. JS CAN try
// and read a declared but undefined variable)
jsFiddle example
But this Javascript will always set Obj to "no Obj"!
var Obj ="I'm here!";
(function() {
var Obj = Obj || "no Obj"; // Obj becomes undefined after "var Obj"...
alert(Obj); // Output: "no Obj"
})();
jsFiddle example
So using this type of short circuit evaluation in Javascript is dangerous, since you can usually only use it in the form
Obj = Obj || {};
Which will fail precisely when you would most want it to work... in the case where Obj is undeclared.
Note: I mention this in the comments of the penultimate example, but it's important to understand the 2 reasons that a variable can be undefined in Javascript.
A variable can be undefined because it was never declared.
A variable can be undefined because it was declared but has not had a value assigned to it.
A variable can be declared using the var keyword. Assigning a value to an undeclared variable creates the variable.
Trying to use an undefined variable that is also undeclared causes a runtime error. Using an undefined variable that has been declared is perfectly legal. This difference is what makes using Obj = Obj || {}; so tricky, since there is no meaningful form of the previous statement if Obj is either undeclared OR it is a previously existing variable.
The mechanics are a bit unusual: Unlike most languages, JavaScript's || operator does not return true or false. Instead, it returns the first "truthy" value or the right-hand value. So for instance:
alert("a" || "b"); // alerts "a", because non-blank strings are "truthy"
alert(undefined || "b") // alerts "b", because undefined is falsey
alert(undefined || false || 0); // alerts "0", because while all are falsy, 0 is rightmost
More in this blog post.
As Darin said, your var Obj = Obj || {}; is probably not a literal quote, more likely something like this:
function foo(param) {
param = param || {};
}
...which means, "if the caller didn't give me something truthy for param, use an object."
var Obj = Obj || {};
I think that the var here is not necessary. It should be:
Obj = Obj || {};
Where Obj is defined elsewhere. This will simply assign Obj to an empty object if it is null or leave as is of not. You might also leave the var keyword in which case it will ensure that the object is declared even if it wasn't before this statement.
Same for the array: if it is null it will assign it to an empty array.
The key to understanding this syntax is that the result of a boolean or (or and) expression in JavaScript is the last-evaluated component. As has been pointed out by other commenters, JavaScript's shortcircuiting is being used along with this feature to conditionally set the value of array or Obj.
Obj = Obj || {};
This means Obj is set to the value of the expression Obj || {}. If Obj is "true", meaning it evaluates to true (for an object, this means it exists), the result of the expression is Obj, because the expression short-circuits. However, if Obj is "false" (non-existent), the second part of the expression must be evaluated. Therefore, in that case, the value of the expression is {}.