Could you explain the below one?
var lib = lib || {};
When do we need to do it? I don't know why lib is used again.
if variable lib has falsy (null, false, 0, undefined, '', NaN) value then assign empty ({}) object. You also can rewrite your example like this
var lib;
if (!lib) {
lib = {}
}
The purpose of this statement is to make sure lib is a truthy value, and alternatively an empty object.
It's used in many function initialization code where the parameter might not be passed by the caller.
One must pay attention though, lib might be true, and will remain true after this statement, instead of being replaced by an empty object.
JavaScript has the following falsy values
false
0 (zero)
"" (empty string)
null
undefined
NaN (not a number)
Now if you have for example something like:
var foo = function(lib){
lib = lib || {};
console.log(lib);
}
Calling foo without parameters (causing lib to be undefined) or with one of the above listed one will print lib as an object (as the {} is a truthy value).
if lib variable is initialited - var lib = lib;, if not - var lib = {}; {} - is an empty object.
If lib is set and not null, false, undefined... Then the new content is whatever lib is before. But if that is not the case, lib will become an empty object.
Related
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.
What is wrong with this code?
var sha = 6;
var secondParameter = dan || sha;
alert(secondParameter);
I tried it with many browsers. No alert.
If I add var dan like this:
var sha = 6;
var dan = 5;
var secondParameter = dan || sha;
alert(secondParameter);
the alert will happen. So the problem in "||". I saw many codes where it use the operator like this! So I have no idea..
You don't have the dan defined. Execution stops at that error. Check the browser console for errors.
When you define dan, execution continues, but that's probably not what you want.
The purpose of such code in JavaScript is to say if dan has a falsy value (any value that evaluates to a false value, i.e. 0, '', null, false, undefined, or NaN), then use the value of sha.
IF defining dan is beyond your responsibility, (i.e some other script should have set it), then you can check for its existence using a construct like follows:
secondParameter = typeof(dan) == 'undefined' ? sha : dan;
(Not tested, hopefully it works. :) anyways, it should give you an idea)
Check here for documentation on logical operators.
Also, this question might give you more insight: Javascript || or operator with a undefinded variable
var sha = 6;
var dan = null;
var secondParameter = dan || sha;
alert(secondParameter);
Try this. You can coalesce using the || operator, but all variables have to be declared in order to be referenced
This is used in a situation where it is given as something like a parameter but isn't assigned a value or it is falsy
falsy being 0, false, null or undefined
For example:
var sha = 6;
var dan = undefined;
var secondParameter = dan || sha;
alert(secondParameter);
You will get 6
A good example to use this would be something like this:
function funcWithCallback(callback){
callback = callback || function(){};
callback();
}
In this example if callback is undefined (or falsy) then set callback as a new instance of a function
Using it in a situation like this will ensure no error
There is a difference in how JavaScript handles undeclared variables (undefined variable) and undefined values. In the following example the variable dan is declared but never set so it's value is undefined the || returns the first true value it can find so if I pass anything but an empty string, 0, false, NaN, undefined or NULL it'll console.log the passed value. Else it'll log "default value".
function test(dan){
console.log(dan || "default value");
return dan===undefined;
}
console.log(test());//default value, then true
console.log(test(22));//22 then false
A more robust way of checking if a variable was passed would be to see if the variable's value is undefined:
function test(dan){
dan = (typeof(dan)==='undefined')?"default value":dan;
}
In your example the variable dan is not declared at all (variable is undefined), that's why you get error "dan is not defined" because dan is not declared at all.
function test(){
return dan===undefined;//ReferenceError: dan is not defined
}
console.log(test());
You could change your code to this:
var sha = 6, dan;//dan is declared here but no value is set
var secondParameter = dan || sha;
console.log(dan===undefined);//true
console.log(secondParameter);//6
If you want to check if a certain object has a property then it'll not throw an error:
function test(){
return window.neverSetOrDeclared===undefined;
}
console.log(test());//true
It will throw an error when you try to check a property of undefined or null:
null.something//throws error
undefined.something//throws error
window.neverSetOrDeclared===undefined//throws error
Explanation: the way this || works is : if first condition is false then it checks second condition. So in order to display second parameter, you'll have to make first parameter null.
var boolTrue = true;
var randomObject;
if (boolTrue)
// this will fire
if (randomObject)
// this will fire, because the object is defined
if (!objectNotDefined)
// this will fire, because there is no defined object named 'objectNotDefined'
Coming from a C++ and C# background, I am very familiar with the basic if(expression) syntax. However, I think it is not very readable to have both expressions (true/false) and have object existence also being a expression. Because now if I see a function like below, i don't know if the data coming in is an object (existence/undefined check) or a boolean.
function(data) {
if (data)
// is this checking if the object is true/false or if the object is in existence?
}
Is this just the way it is? I mean, is there anyway to easily read this? Also, where is this documented anywhere in the JS spec (curious)?
In Javascript everything is "true" (or "truthy" to be more precise using Javascript parlance) except false, 0, undefined, null, NaN and empty string.
To avoid confusion use:
if (data === true) // Is it really true?
and
if (typeof data === 'undefined') // Is the variable undefined?
You can check for (non-)existence separately:
if ( typeof variable == 'undefined' ) {
// other code
}
However, the syntax you show is commonly used as a much shorter form and is sufficient in most usecases.
The following values are equivalent to false in conditional statements:
false
null
undefined
The empty string ”
The number 0
The number NaN
It checks whether it is truthy.
In JavaScript, everything is truthy except false, 0, "", undefined, null and NaN.
So, true will pass, as well as any object (also empty objects/arrays/etc).
Note that your third comment is true if you mean "declared but not defined" - a variable that has never been declared throws a ReferenceError on access. A declared, non-defined variable (var something;) is undefined (so, not truthy) so it will indeed pass the condition if you negate it.
I have this code in JavaScript:
var JSON;
JSON||(JSON={});
Can you tell what this code is doing?
var JSON is declaring a global (or other scope) variable.
JSON||(JSON={}); is first checking to see if JSON evaluates to true or false, and if false, then JSON is set to an empty object;
It is pretty pointless in that context,
var JSON;
creates a variable named JSON
The second part,
JSON||(JSON={});
is equivalent to
if(!JSON){
JSON = {};
}
This can all be skipped and written as
var JSON = {};
It scopes a variable called JSON, then uses the shortcircuit nature of the || operator to assign an empty object to said variable unless that variable has a truthy value.
Its just making JSON an empty object.
This code is doing the following:
Declare variable JSON (JSON === undefined)
Assign an empty object ({}) to JSON if JSON is a falsey value.
Falsey values include: null, undefined, "" (empty string), 0, NaN, false.
JSON has been declared via var JSON, so is set to undefined, meaning that the right hand-side of the operation JSON||... will be executed. In other words, all the code is achieving is:
var JSON = {};
I think this says : if the var 'JSON' is null create a blank javascript obect.
I often find myself using inline initialization (see example below), especially in a switch statement when I don't know which case loop will hit. I find it easier to read than if statements.
But is this good practice or will it incur side-effects or a performance hit?
for (var i in array) {
var o = o ? o : {}; // init object if it doesn't exist
o[array[i]] = 1; // add key-values
}
Is there a good website to go to get coding style tips?
Another commonly used pattern to do the same, is the use of the Logical OR || operator (a little bit more readable than your ternary IMHO):
//...
var obj = o || {};
This operator will return its second operand if the first one evaluates to false, otherwise it will return the first one.
Is safe to use it when you expect an object, since those falsy values are null, undefined, NaN, 0, a zero-length string, and of course false.
I find it useful to set default values on function arguments, when of course any of the falsy values are expected as valid by the function:
function test (arg1) {
arg1 = arg1 || "default value";
//..
}
Why not just declare it outside the loop?
var o = {};
for (var i in array) {
o[array[i]] = 1;
}
Otherwise no, I don't see a problem with what you're doing.