Init object in javascript using || operator [duplicate] - javascript

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

Related

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

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 creation? [duplicate]

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.

What is this in javascript: "var var1 = var1 || []"

I just want to increase my core javascript knowledge.
Sometimes I see this statement but I don't know what it does:
var var1 = var1 || [];
What does it means and/or what's it for, and how do you use it?
Thank you.
Basically, it looks to see if a variable var1 already exists and is "truthy". If it is, it assigns the local var1 variable its value; if not, it gets assigned an empty array.
This works because the JavaScript || operator returns the value of the first truthy operand, or the last one, if none are truthy. var1 || var2 returns var1 if it's truthy, or var2 otherwise.
Here are some examples:
var somevar;
somevar = 5 || 2; // 5
somevar = 0 || 2; // 2
somevar = 0 || null; // null
Values that aren't "truthy": false, 0, undefined, null, "" (empty string), and NaN. Empty arrays and objects are considered truthy in JavaScript, unlike in some other languages.
It assigns an empty array to var1, if the boolean representation of it is false (for example it hasn't been initialized).
Basically if var1 is NULL or false, var1 will be set to an empty array.
The logical operators in JavaScript actually evaluate to one of the two objects. When you use a || b it evaluates to b if a is false, or to a if a is true. Thus a || [] will be a if a is any value that is true, or [] if a is any value that is false.
It's much more obvious to use if (!a) { a = [] };
Javascript or (||) works a bit differently to some other languages, it returns the first "truthy" value instead of a boolean. This is being used in this case to say "Set the value of var1 to var1, but if that value is "falsey" set it to []".
This is often used to set a "default" value to a variable that may or may not be set already, such as an argument to a function.
The || operator evaluates the first of its operands that is "truthy".
[] is an empty array. ([ "Hi!" ] is an array of one string)
Therefore, the expression x || [] evaluates to x if it's "truthy" or an empty array if it isn't.
This allows the var1 parameter to be optional.
The statement assigns an empty array to var1.
longer answer and explanation:
This happens because var1 is not initialized at that time. Non-initialized is a falsy value.
take this statement:
var1 = var1 || [];
If var1 is not initialized it becomes an empty array, it if is an empty array nothing happens as its assigned to an empty array, if var1 is false, null, or any other value that javascript things of as false, it becomes an empty array, if var1 is anything other value, nothing happens as it is assigned to itself. (thanks pst for the link).
In short, its a stupid statement that's neither readable nor useful, but you're smart for wanting to know what it means. :)
While this has been pointed out as 'being a silly statement', I present the following two counters:
(Just to keep people on their toes and reinforce some of the "finer details" of JavaScript.)
1)
var is the variable is already local. E.g.
function x (y) {
var y = y || 42 // redeclaration warning in FF, however it's "valid"
return y
}
x(true) // true
x() // 42
2)
var is function-wide annotation (it is "hoisted" to the top) and not a declaration at the point of use.
function x () {
y = true
var y = y || 42
}
x() // true
I do not like code like either of the preceding, but...
Because of the hoisting, and allowed re-declarations, the code in the post has these semantics:
var var1
if (!var1) {
var1 = []
}
Edit I am not aware of how "strict mode" in Ed.5 influences the above.

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