Javascript object creation? [duplicate] - javascript

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.

Related

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.

Meaning of || in javascript argument [duplicate]

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.

JavaScript object detection

I am currently practicing javascript and I'm currently having trouble with object detection. I want to create an object and detect whether it exists. Below is some example code I am currently using.
The code sample below is how I am creating my object.
var obj = obj || {};
Should I be using this?
if (typeof obj !== "undefined") {
// code
}
Or this?
if (obj !== null) {
}
The value undefined means that the variable has not been assigned a value. The value null indicates that it has been assigned the value null. The === operator (and its negation, !==) prevent type coercion.
Which is right? It all depends on what you are trying to accomplish. Both undefined and null are "falsy" values, meaning that each one evaluates to false in a boolean context (as do false, 0, and the empty string).
Note that if obj is null, then typeof obj is not "undefined".
The usual practice is to use:
var obj = obj || {};
When that code runs, you can be certain that obj has been defined (because of the var declaration), though it may not have been assigned a value.
If the value of obj resolves to a "falsey" value, then you will assign a reference to a new object.
Possible outcomes are:
If obj has not been assigned a value, a new object reference is assigned.
If obj has previously been assigned a "falsey" value, it will be replaced by a new object reference (which may mess with whatever code assigned it the falsey value).
If obj has previously been assigned a "truethy" primitive value, the following assignments of properties to obj will throw an error and script execution will stop.
if obj is already a reference to an object other than null, then subsequent assignments of properties will be to that object. Depending on the type of object, things may be ok. Or not. Presumably something outside your control created the object and so may modify or destroy it without your knowledge. What will you do?
It is not possible in javascript to deal, in general, with cases 2 and 3, or 4 where it's not your obj you're dealiing with. So use a name that is unlikely to clash with any other and hope you get #1 or #4 and things go well.
Incidentally, code added after yours may still result (more or less) in #4, even if you had #1 at the point the code is executed.
There is no additional benefit to tests like:
if (typeof obj == 'undefined')
because the outcome is essentially the same.

Init object in javascript using || operator [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.
Sometimes I see in javascript code something like this:
var myObj = myObj || {};
So, what actually happen here? I suppose || operator returns true or false, but it's not correct.
The || operator returns the left operand if it evaluates as true, otherwise it evaluates and returns the right operand. In other words, a || b is equivalent to a ? a : b except that a is only evaluated once.
To understand the || operator, let's first look at a fairly basic example. The logical OR operator may be used to provide a default value for a defined variable as follows:
var bar = false,
foobar = 5,
foo = bar || foobar; // foo = 5
In this case, foo will only be assigned the value of foobar if bar is considered falsy. A falsy value could be considered being equal to 0, false, undefined, null, NaN or empty (e.g "").
This initializes myObj unless it is already defined.
You can use this construct to get the object that is not null, undefined, etc. This is used in cases where you use myObj later on in the code which requires it to be an object. If, for some reason, myObj is undefined prior to this line, re-assigning it leaves it undefined or null, in which case it would be assigned {}.
You can think of this as:
// If the object is already defined
if (myObj)
var myObj = myObj;
// It was undefined or null, so assign an empty object to it.
else
var myObj = {};
The OR op (||) will return the first non-empty/false parameter.
In the case specified, if myObj is false or null, it will be set to an empty object (the {} brackets are used to create objects)
|| is a short circuit operator. If the first operand evaluates to true the second is not evaluated.
Thus JS a || b is something like c# a ?? b
if myObj is undefined or null then it evaluates the expression on the right side of || which creates a new empty object
so myObj is either myObj if it is not null or an empty object if myObj is null
i hope you understand what i mean

JavaScript Object instantiation

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 {}.

Categories

Resources