This question already has answers here:
What does var x = x || {} ; [duplicate]
(6 answers)
Closed 9 years ago.
Im looking at some Backbone.js examples and they have var app = app || {}; at the top of all .js files. I understand the literal meaning of this, but what does it do in reference to everything else?
Edit: you guys are really really fast.
It will define the variable app to an empty object if it is not already defined.
This works because being undefined evaluates to false in Javascript.
If it is defined, it may still be re-defined as an empty object if it has a value which evalutes to false, such as an empty string.
The || operator in javascript will return the first operand if it is "truthy". If not, it will return the second operand. If app has not been assigned, it will be undefined, which is "falsey". Thus if it is not defined or is otherwise falsey, an empty object {} will be assigned to app.
This means "define app as an empty object if it's not already defined".
The OR operator in JavaScript does not necessarily yield a boolean. If the left-hand side of the expression yields false then the assignment takes the right-hand side of the expression.
If app is already defined, the it does nothing.
If app is not defined, then it's equivalent to var app = {};
Related
This question already has answers here:
Is there a "null coalescing" operator in JavaScript?
(19 answers)
Closed 4 years ago.
I have a function that may return a value or may return null and I want to assign it to a variable. So at the moment I've got
someVar = (someFun())
? someFun()
: "foo";
Is there a shorterer way of doing it, where I don't have to call the function twice, or add an extra variable like:
funResult = someFun();
someVar = (funResult)
? funResult
: "foo";
Basically, something like:
someVar = someFun() | "foo"
The idiomatic way is
someVar = someFun() || "foo";
The || operator will yield the value of the left-hand expression if it's truthy. If not, it will move on to evaluate the right-hand side, and return its value.
For those unfamiliar with the term "truthy", in JavaScript it means values that are not considered by the language to be implicitly false. The implicitly false values are 0, NaN, false (of course), "", null, and undefined. Any reference to an object, even if it's completely empty, is considered to be "truthy".
In your specific example, the || approach is to be preferred because it means you only call someFun() once.
This question already has answers here:
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
JS checking deep object property existence [duplicate]
(2 answers)
Closed 6 years ago.
I dont know if a.b is set. I want to do something only if a.b[0].c is true. I can do something like this:
if (a.b && a.b[0] && a.b[0].c) {
// ...
}
Is there a shortcut to check nested existence? Can I simplify this kind of condition?
I used to code golf, and one of the tricks we used is the following.
(myArray || [])[0] || 0
First, myArray || [] is evaluated, if myArray exists, this returns it, if it doesn't, then it returns an empty array. Let's say myArray isn't defined. Next, the [][0] || 0 expression gets evaluated ans because [][0] is undefined, this returns 0.
In your case it could be used the following way:
((a.b || [])[0] || {}).c || {}
This returns an empty object if something's undefined.
I'm not saying you should use this (in fact, you shouldn't), I just want to show you, that there is a smaller solution.
Update:
If tc39 gets through, then you'll have a much better solution using optional chaining:
a.b?[0]?.c
This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 6 years ago.
I have written a simple function that nullifies itself after its first call:
var nullify = function(){
nullify = null;
return 1;
};
If I call it two times, like this:
console.log(nullify());
console.log(nullify);
Then the 1st expression will return 1, and the other will evaluate to null. All clear up to this point.
If I however do it in a single expression and wrap it in a function:
var fun = function(f){
return f() && !f;
}
Then, for some reason:
console.log(fun(nullify));
evaluates to false, while I would expect it to be true, since 1st operand will return 1 and the other, as a negation of null, true.
The evaluation of the right-hand operand occurs when the nullify functiion has already called nullify = null, is that right? What am I missing?
What am I missing?
That your fun function is testing the variable f, which still is bound to the function you passed in, not the variable nullify (which has the value null indeed).
This question already has answers here:
What does "options = options || {}" mean in Javascript? [duplicate]
(5 answers)
Closed 9 years ago.
So I am looking over a project which includes the following line of javascript:
window.negotiationApp = window.negotiationApp || {};
Can anyone explain might be going on with this line of code?
Update
So now that I understand what this line of code is doing, my question maybe unique in asking the following:
There is no negotiationApp object in the javascript code. window.negotiationApp will always be set to an empty object, it seems the developer is really just using this as a namespace or container for other objects. Is this a common javascript practice?
it makes sure that window.negotiationApp is set. If window does not have this property then it initializes it to be {} (an empty object), otherwise, it does nothing.
It's an idiom that basically means, if window.negotiationApp doesn't exist, set it to {}. You might do that so future info doesn't return undefined or something.
Ensures window.negotiationApp object is not undefined.
window.negotiationApp = window.negotiationApp || {};
Means if window.negotiationApp is defined then use it or assign window.negotiationApp an empty object.
if(window.negotiationApp) {
window.negotiationApp = window.negotiationApp;
}
else {
window.negotiationApp = {};
}
since this variable is set on the global scope, it makes sure not to override an existing one if there is any.
so it basically says, if there is already a negotiationApp variable defined - use it, if not create a new one.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
null coalescing operator for javascript?
What does “options = options || {}” mean in Javascript?
Can someone explain me this expression? I stumbled accros the javascript line of code and I wondered what it means.
var node = element.node || element[element.length - 1].node;
node get's used like this below:
if (node.nextSibling) {
node.parentNode.insertBefore(this.node, node.nextSibling);
} else {
node.parentNode[appendChild](this.node);
}
At first i though node should be a boolean or something but it's not.
Am I correct if i think that the meaning is: node is element.node but if the node attribute is undefined node is the last element in the array of element?
Your understanding is along the right lines; be aware that even if element.node is defined, but is a falsey value (0, false etc.) that element[element.length - 1].node will be assigned to node instead.
It means, if element.node has a value represents True in boolean expressions, node will be element.node, otherwise it will be element[element.length - 1].node
Simple answer: it means OR :)
Reference: http://www.w3schools.com/js/js_operators.asp
It means OR
for example:
if this || that
means "if this or that"
So when the computer comes to the "||" part of your code, if the statement before it is true, it will stop reading that if statement and automatically execute the code underneath.
If the item before that "||" is false, then it will check the next one, and so on...