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.
Related
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.
Assuming a Javascript object has a function:
function Foo() {
this.a = 32;
this.bar = function (){
alert("Hello World!");
}
}
How does JSON.stringify() deal with the bar function? Is it just ignored? Is this standard practice? What does JSON converts and doesn't convert into the Json string?
Rem: I don't know why people downvoted my question, it is obvious one should not stringify an object with a function. I was just trying to understand the default behavior.
JSON.stringify simply changes functions passed into null if passed into an array, and does not include the property in at all if in an object. It makes no attempt to replicate the function, not even in string form.
For example, see this:
JSON.stringify([function () {}]); // "[null]"
JSON.stringify({ x: function () {} }); // "{}"
If you attempt to stringify a function itself, it's not a valid JSON value, which means that JSON.stringify can't make a valid JSON string:
JSON.stringify(function () {}); // undefined
This is specified as part of the ECMAScript specification, though the actual wording of it is rather complex. However, a note is included that summarises this:
NOTE 5
Values that do not have a JSON representation (such as
undefined and functions) do not produce a String. Instead they produce the undefined value. In arrays these values are represented as
the String null. In objects an unrepresentable value causes the
property to be excluded from stringification.
I came across this line and I'm unsure how it does what it does. The data portion is a json object and later on, the "myarray" variable is used to assign new variables to an array.
The "myItems" object is used to iterate through a .map function over the objects in the data object. But I have no idea how this all gets assigned through the code below:
var myItems = data || [], myarray;
It declares two global variables myItems and myarray. My items is assigned data if data is not undefined, if data is undefined it assigns an empty array to myItems.
The || operator can be used during assignment due to the truthy or falsey nature of variables in Javascript.
Several values equate to false in Javascript such as an empty string "" or undefined. Others such as a String literal != "" (Example "Test") and objects will equate to true. When used in assignment the section of code proceeding the || will not be evaluated if the first expression equates to true.
This link gives a better description of truthy and falsey.
Another way to write this would be:
var myItems;
if (data) {
myItems = data;
} else {
myItems = [];
}
var myarray;
This line of code does the following:
it declares myarray and myItems variables.
data || [] means take data if evaluates to true (not empty), otherwise take new empty array. This is kind of javascript mnemonic to provide fallback/default values.
Assigns the result of previous step to myItems
So, it's better written as
var myarray;
var myItems = data || [];
Here, you're defining two variables called data and myarray (take note of the comma).
The || (logical OR operator) is being lightly abused here. The statement
var myItems = data || [];
Will assign the value of data to myItems if data is not falsy. If it is falsy, however, myItems will be initialised as an empty array with []. Due to lazy evaluation, if data != false, the rest of the statement is not executed.
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.
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 {}.