What does ||{} mean in javascript? - javascript

I'm working on a project using Easel JS. Opened up the Easel file and the very first line of code confused me:
this.createjs = this.createjs||{};
I know that createjs is invoked when you're setting up your canvas or, for example, creating a bitmap to add to the canvas. But I don't understand the syntax of this line - assign this.createjs or (what I guess is) a blank object to this.createjs?

this.createjs = this.createjs||{};
If this.createjs is not available/ any falsy value then you are assigning {} empty object to this.createjs.
It's more like,
var a,
b;
b = a || 5;
Since a is not having any value currently, 5 will be assigned to b.

Correct. This ensures that if this.createjs doesn't already exist, an empty object is assigned to it. The || is an or operator - if this.createjs on the left-hand-side evaluates to falsy, it will assign the right-hand-side instead.

this.createjs = this.createjs||{};
If this.createjs is falsy, this.createjs will be a new empty object
You could have replace it by
if (!this.createjs){
this.createjs = {};
}

|| means or.
In that context means this.createjs equals if exists/not null/defined this.createjs other way {}

Related

Concatenating a declared but not defined variable

Out of curiosity I did this simple concatenation:
let a;
a+="hello"
console.log(a)
It returns "undefinedhello"
I get that a was basically the string "undefined", or is it converted to a string when concatenating? Is there something to learn here?
let a="";
a+="hello"
console.log(a)
since you are creating a variable here so the default value becomes undefined . You need to assign a value over there.
check here

Setting up variable to return function value or false

I wasn't sure how to properly word the title for this question but jumping right into it,
Using the the ? : operator I setup a JavaScript variable and an if statement like so:
var test = callsAFunction ? test : false;
if I do this, will test equal whatever the function returns here? Or will it be undefined since it's "Technically" not set yet?
What I'm trying to do is set a variable to either what data it gets back and is run through a function, or set it to Boolean false so it will process through my Boolean check as an error. I figured this approach was best but I'm running into issues determining how to go about this. Below are my code snippets:
var hash = self.getHashFromMasterRecords(d[0]);
if(hash === false){
done("Can't find master record hash", self.requestData, self);
}
Obviously it needs to turn false as a Boolean in order to pass as an error. I want to do this without having to call the function more than 1 time for this sequence.
So if I do var hash = self.getHashFromMasterRecords(d[0]) ? hash : flase; would hash return the value? Or undefined?
Thank you ahead of time, if I need to post more info let me know.
The syntax:
var a = (b) ? c : d;
Will set a equal to c if b is evaluates to something truthy, and d if b evaluates to something falsy. If I understand you correctly, you want to set a variable to the return value of a function, and if that function fails, set it to some default value. To do that, use ||:
var a = b() || 'error occurred!';
In the line above, if b() evaluates to something falsy, a will get the value of error occurred!. If b() evaluates to something truthy, it will get the return value of b().
It would be undefined. As long as your function returns a falsey value when it returns you can use the or (||) operator:
var hash = self.getHashFromMasterRecords(d[0]) ?? false;
Although, if that is a concrete example there is little value in the above code as you'd already have a falsey value by just storing the result from the function.

First line of Javascript file is var w = w || {};

This is the very first line of a JavaScript file I am modifying and and what does it do? jQuery is also used in the file.
var w = w || {};
From what I know the || is a logical operator this is a quote from the Mozilla documentation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
You should see that line as a shortened version of this.
// declare w as a variable
var w;
// if w is already declared, leave it
if (!w) {
// if not make it an empty object
w = {};
}
In the global context (where I'm sure this is defined), using var will not overwrite an existing global.
So basically, you are ensuring that there is a var by the name of w that you are able to store properties on.
It assigns w to w if it contains a value that is not false, else, it sets w as an empty object.
It sets w to w's current value if w is "truthy", and w to an empty object if w is "falsy."
Falsy values include NaN, null, undefined, 0, empty strings, and of course false.
Everything else is truthy.
Essentially, it makes sure that w is an object if it is not one already.
This is to check if 'w' is truthy or falsy.
'w' is falsy if it has any of the values:
false
0
""
null
undefined
NaN
The expression (w || {}) will return 'w' if it is not a falsy value. Otherwise, it will return an empty array. So when you assign it to 'w' in the expression: var w = w || {};
It is just a way of making sure 'w' isn't a falsy value and doesn't throw any errors if it gets used later on in your code.

Set JavaScript variable = null, or leave undefined?

When declaring variables at the top of the JavaScript function, is it best practice to set them equal to null, or leave as 'undefined'? Another way to ask, what circumstances call for each option below?
Option A:
var a = null,
b = null;
Option B:
var a,
b;
It depends on the context.
"undefined" means this value does not exist. typeof returns "undefined"
"null" means this value exists with an empty value. When you use typeof to test for "null", you will see that it's an object. Other case when you serialize "null" value to backend server like asp.net mvc, the server will receive "null", but when you serialize "undefined", the server is unlikely to receive a value.
I declare them as undefined when I don't assign a value because they are undefined after all.
Generally, I use null for values that I know can have a "null" state; for example
if(jane.isManager == false){
jane.employees = null
}
Otherwise, if its a variable or function that's not defined yet (and thus, is not "usable" at the moment) but is supposed to be setup later, I usually leave it undefined.
Generally speak I defined null as it indicates a human set the value and undefined to indicate no setting has taken place.
I usually set it to whatever I expect to be returned from the function.
If a string, than i will set it to an empty string ='', same for object ={} and array=[], integers = 0.
using this method saves me the need to check for null / undefined. my function will know how to handle string/array/object regardless of the result.
The only time you need to set it (or not) is if you need to explicitly check that a variable a is set exactly to null or undefined.
if(a === null) {
}
...is not the same as:
if(a === undefined) {
}
That said, a == null && a == undefined will return true.
Fiddle
Be careful if you use this value to assign some object's property and call JSON.stringify later* - nulls will remain, but undefined properties will be omited, as in example below:
var a, b = null;
c = {a, b};
console.log(c);
console.log(JSON.stringify(c)) // a omited
*or some utility function/library that works in similar way or uses JSON.stringify underneath
There are two features of null we should understand:
null is an empty or non-existent value.
null must be assigned.
You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value.
example:-
let a = null;
console.log(a); //null
You can use ''; to declaring NULL variable in Javascript

explaining this declaration of the global namespace

I see this quite a lot at the top of scripts but I'm not completely sure what it means, can anyone explain?
var whatevername = whatevername || {};
It uses the OR operator to set default values. If whatevername has been set it will be used, otherwise a new empty object will be used.
An example:
function sayHi(options){
options = options || {};
if (options.useAlert){
alert("hi");
} else {
console.log("hi");
}
}
In this case you can always use the options parameter, even if it isn't passed to the function:
sayHi();
sayHi({"useAlert": true});
In the first case {} will be used and options.useAlert will be undefined. In the if statement that's the same as it being set to false and console.log will be used to print.
The OR operator is usually used like this:
if (hasAnEmailAddress || hasAPhoneNumber) {contactPerson()}
If hasAnEmailAddress is true the operator will return the value of hasAnEmailAddress instead of hasAPhoneNumber. If it isn't true the value of the second argument, hasAPhoneNumber will be returned.
That logic is used when setting default values: If the first argument is falsy return the second argument - even if it isn't a boolean value.
it initializes whatevername with an empty object if whatevername hasn't already been initialized.
Equivalent code
if(!whatevername) whatevername = {}
In a lot of languages, you will see this done with a ternary operator, which I think makes it very clear what's going on. Example:
var whatevername = (whatevername != NULL) ? whatevername : {};
In Javascript, if the || operator evaluates to truthy, it will not return a boolean value as one might expect, but the value of the operand which was last evaluated. Therefor, if whatevername is null, it will return a new object, otherwise it will return whatevername. Ruby does this as well, just to name another example of this behaviour.
This is a default value statement. || is the symbol for OR, as you probably know.
The statement reads "set whatevername to whatevername OR an empty object". The OR will pick the first of the two objects that reads to a truthy value (not empty, not false). If whatevername was set, you'll get whatevername. If not (or if set to null), you'll get an empty object.

Categories