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.
This code is doing the following:
JSON (JSON === undefined){}) 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 = {};
undefined because the variable is declared via var JSON. If it had another value prior to that declaration it won't matter since JSON||.. runs after that.var gets hosted and doesn't reset a variable with a value defined earlier in the scope. I've seen: function (foo) { var foo … } a number of times. The var is redundant because arguments are locally scoped automatically.I think this says : if the var 'JSON' is null create a blank javascript obect.
null or undefined or any other falsy value. and if it is it assigns a JavaScript object. There is no JSON there (except as the name of a poorly named variable).
var JSON = {};, which creates a new object and assigns it to the variableJSON.