JavaScript Object instantiation - javascript

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 {}.

Related

JavaScript namespace object literal

I've recently come across JavaScript Namespaces and how you can use them to create namespaces like other popular OOP languages. I have confusion on how they are declared. For example,
var myNamespace = myNamespace || {};
creates a namespace called myNamespace if it hasn't already been created. If it was created, just pass it into var myNamespace.
I have trouble understanding what myNamespace || {} actually does.
Wouldn't myNamespace be undefined at first? How would you compare that in a Boolean expression.
Also, how does the object literal {} work? Does it create an empty object and assign that to myNamespace to work as a namespace?
I've tried looking for the answer on SO, but there's too much saturation about the practices on how to declare different types of namespaces.
Although || was originally intended to work with booleans, it is implemented in a very handy way that allows it to work to set default values:
function or(a, b) {
if (a) return a
else return b
}
You can test this in your head and see that it works with booleans: if a is true, the result is true so the result is the same as a. If a is false then the result depends on b.
Variable declarations with var in JavaScript work a bit strangely. You are allowed to redeclare a variable with the same identifier in the same scope. So the way the code works is:
If myNamespace is already declared, you redeclare the variable without assigning to it yet. You get the value from the old declaration of myNamespace. This value is assumed to be truthy, so the || will return it.
If myNamespace is not yet declared, you declare it and then myNamespace will be undefined, a falsy value. So the || will return the second value, the {}, and that is the value that will get assigned to myNamespace.
It may make sense to read it in two separate steps:
//Declare the variable if it doesn't exist,
//without overwriting an existing value
var myNamespace
//Take the value of myNamespace (undefined if it didn't exist yet)
//and replace it with {} if it is falsy
myNamespace = myNamespace || {}
var myNamespace = myNamespace || {};
Does exactly what you said it does.
|| is an or operator as seen here
So what this is doing is, saying var myNamespace = myNamespace however, if myNamespace is undefined, then it will just go to the right hand side of the operator and just create an empty object like this (you were right about this):
var myNamespace = {}
Let me know if I seem confused, I think I addressed your points.
Take a look at the definition of || from here:
expr1 || expr2
Returns expr1 if it can be converted to true; otherwise, returns
expr2.
Now try
console.log(undefined == true);
This will print false, which means that undefined cannot be converted to true (we are using the == operator to let JavaScript use type coercion). As a result, if myNamespace is undefined, an empty object literal will by assigned to it (which is equivalent to expr2 from the quote).

Check if value is assigned [duplicate]

Which method of checking if a variable has been initialized is better/correct?
(Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
You want the typeof operator. Specifically:
if (typeof variable !== 'undefined') {
// the variable is defined
}
The typeof operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison === instead of simple equality ==, see:Which equals operator (== vs ===) should be used in JavaScript comparisons?
In many cases, using:
if (elem) { // or !elem
will do the job for you!... this will check these below cases:
undefined: if the value is not defined and it's undefined
null: if it's null, for example, if a DOM element not exists...
empty string: ''
0: number zero
NaN: not a number
false
So it will cover off kind of all cases, but there are always weird cases which we'd like to cover as well, for example, a string with spaces, like this ' ' one, this will be defined in javascript as it has spaces inside string... for example in this case you add one more check using trim(), like:
if(elem) {
if(typeof elem === 'string' && elem.trim()) {
///
Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object {} are always true.
I create the image below to show a quick brief of the answer:
In JavaScript, a variable can be defined, but hold the value undefined, so the most common answer is not technically correct, and instead performs the following:
if (typeof v === "undefined") {
// no variable "v" is defined in the current scope
// *or* some variable v exists and has been assigned the value undefined
} else {
// some variable (global or local) "v" is defined in the current scope
// *and* it contains a value other than undefined
}
That may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code's behavior and understand it yourself (if you care about such things):
if ("v" in window) {
// global variable v is defined
} else {
// global variable v is not defined
}
This, of course, assumes you are running in a browser (where window is a name for the global object). But if you're mucking around with globals like this you're probably in a browser. Subjectively, using 'name' in window is stylistically consistent with using window.name to refer to globals. Accessing globals as properties of window rather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.
In the majority of cases you would use:
elem != null
Unlike a simple if (elem), it allows 0, false, NaN and '', but rejects null or undefined, making it a good, general test for the presence of an argument, or property of an object.
The other checks are not incorrect either, they just have different uses:
if (elem): can be used if elem is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).
typeof elem == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property.
This is the only check that won't throw an error if elem is not declared (i.e. no var statement, not a property of window, or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.
Also useful is a strict comparison against undefined:
if (elem === undefined) ...
However, because the global undefined can be overridden with another value, it is best to declare the variable undefined in the current scope before using it:
var undefined; // really undefined
if (elem === undefined) ...
Or:
(function (undefined) {
if (elem === undefined) ...
})();
A secondary advantage of this method is that JS minifiers can reduce the undefined variable to a single character, saving you a few bytes every time.
Check if window.hasOwnProperty("varname")
An alternative to the plethora of typeof answers;
Global variables declared with a var varname = value; statement in the global scope
can be accessed as properties of the window object.
As such, the hasOwnProperty() method, which
returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it)
can be used to determine whether
a var of "varname" has been declared globally i.e. is a property of the window.
// Globally established, therefore, properties of window
var foo = "whatever", // string
bar = false, // bool
baz; // undefined
// window.qux does not exist
console.log( [
window.hasOwnProperty( "foo" ), // true
window.hasOwnProperty( "bar" ), // true
window.hasOwnProperty( "baz" ), // true
window.hasOwnProperty( "qux" ) // false
] );
What's great about hasOwnProperty() is that in calling it, we don't use a variable that might as yet be undeclared - which of course is half the problem in the first place.
Although not always the perfect or ideal solution, in certain circumstances, it's just the job!
Notes
The above is true when using var to define a variable, as opposed to let which:
declares a block scope local variable, optionally initializing it to a value.
is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
At the top level of programs and functions, let, unlike var, does not create a property on the global object.
For completeness: const constants are, by definition, not actually variable (although their content can be); more relevantly:
Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared.
The value of a constant cannot change through reassignment, and it can't be redeclared.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
Since let variables or const constants are never properties of any object which has inherited the hasOwnProperty() method, it cannot be used to check for their existence.
Regarding the availability and use of hasOwnProperty():
Every object descended from Object inherits the hasOwnProperty() method. [...] unlike the in operator, this method does not check down the object's prototype chain.
How to check if a variable exists
This is a pretty bulletproof solution for testing if a variable exists and has been initialized :
var setOrNot = typeof variable !== typeof undefined;
It is most commonly used in combination with a ternary operator to set a default in case a certain variable has not been initialized :
var dark = typeof darkColor !== typeof undefined ? darkColor : "black";
Problems with encapsulation
Unfortunately, you cannot simply encapsulate your check in a function.
You might think of doing something like this :
function isset(variable) {
return typeof variable !== typeof undefined;
}
However, this will produce a reference error if you're calling eg. isset(foo) and variable foo has not been defined, because you cannot pass along a non-existing variable to a function :
Uncaught ReferenceError: foo is not defined
Testing whether function parameters are undefined
While our isset function cannot be used to test whether a variable exists or not (for reasons explained hereabove), it does allow us to test whether the parameters of a function are undefined :
var a = '5';
var test = function(x, y) {
console.log(isset(x));
console.log(isset(y));
};
test(a);
// OUTPUT :
// ------------
// TRUE
// FALSE
Even though no value for y is passed along to function test, our isset function works perfectly in this context, because y is known in function test as an undefined value.
Short way to test a variable is not declared (not undefined) is
if (typeof variable === "undefined") {
...
}
I found it useful for detecting script running outside a browser (not having declared window variable).
There is another short hand way to check this, when you perform simple assignments and related checks. Simply use Conditional (Ternary) Operator.
var values = typeof variable !== 'undefined' ? variable : '';
Also this will be helpful, when you try to declare the Global variable with instance assignment of the reference variable.
If you wanted to check variable shouldn't be undefined or null. Then perform below check.
When the variable is declared, and if you want to check the value, this is even Simple: and it would perform undefined and null checks together.
var values = variable ? variable : '';
It depends if you just care that the variable has been defined or if you want it to have a meaningful value.
Checking if the type is undefined will check if the variable has been defined yet.
=== null or !== null will only check if the value of the variable is exactly null.
== null or != null will check if the value is undefined or null.
if(value) will check if the variable is undefined, null, 0, or an empty string.
Try-catch
If variable was not defined at all (for instance: external library which define global variable is not yet loaded - e.g. google maps), you can check this without break code execution using try-catch block as follows (you don't need to use strict mode)
try{
notDefinedVariable;
} catch(e) {
console.log('detected: variable not exists');
}
console.log('but the code is still executed');
notDefinedVariable; // without try-catch wrapper code stops here
console.log('code execution stops. You will NOT see this message on console');
BONUS: (referring to other answers) Why === is more clear than == (source)
if( a == b )
if( a === b )
The highest answer is correct, use typeof.
However, what I wanted to point out was that in JavaScript undefined is mutable (for some ungodly reason). So simply doing a check for varName !== undefined has the potential to not always return as you expect it to, because other libs could have changed undefined. A few answers (#skalee's, for one), seem to prefer not using typeof, and that could get one into trouble.
The "old" way to handle this was declaring undefined as a var to offset any potential muting/over-riding of undefined. However, the best way is still to use typeof because it will ignore any overriding of undefined from other code. Especially if you are writing code for use in the wild where who knows what else could be running on the page...
if (typeof console != "undefined") {
...
}
Or better
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
Works in all browsers
To contribute to the debate, if I know the variable should be a string or an object I always prefer if (!variable), so checking if its falsy. This can bring to more clean code so that, for example:
if (typeof data !== "undefined" && typeof data.url === "undefined") {
var message = 'Error receiving response';
if (typeof data.error !== "undefined") {
message = data.error;
} else if (typeof data.message !== "undefined") {
message = data.message;
}
alert(message);
}
..could be reduced to:
if (data && !data.url) {
var message = data.error || data.message || 'Error receiving response';
alert(message)
}
To check if a variable has been declared/set I did this dirty trick.
I haven't found a way to extract the code to a function, even with eval. Se this comment below for an explanation about why.
"use strict";
// var someVar;
var declared;
try {
someVar;
declared = true;
} catch(e) {
declared = false;
}
if (declared) {
console.log("someVar is declared; now has the value: " + someVar);
} else {
console.log("someVar is not declared");
}
The most robust 'is it defined' check is with typeof
if (typeof elem === 'undefined')
If you are just checking for a defined variable to assign a default, for an easy to read one liner
you can often do this:
elem = elem || defaultElem;
It's often fine to use, see: Idiomatic way to set default value in javascript
There is also this one liner using the typeof keyword:
elem = (typeof elem === 'undefined') ? defaultElem : elem;
Null is a value in JavaScript and typeof null returns "object"
Therefore, accepted answer will not work if you pass null values. If you pass null values, you need to add an extra check for null values:
if ((typeof variable !== "undefined") && (variable !== null))
{
// the variable is defined and not null
}
In the particular situation outlined in the question,
typeof window.console === "undefined"
is identical to
window.console === undefined
I prefer the latter since it's shorter.
Please note that we look up for console only in global scope (which is a window object in all browsers). In this particular situation it's desirable. We don't want console defined elsewhere.
#BrianKelley in his great answer explains technical details. I've only added lacking conclusion and digested it into something easier to read.
It is difficult to distinguish between undefined and null. Null is a value you can assign to a variable when you want to indicate that the variable has no particular value. Undefined
is a special value which will be the default value of unassigned variables.
var _undefined;
var _null = null;
alert(_undefined);
alert(_null);
alert(_undefined == _null);
alert(_undefined === _null);
you can use the typeof operator.
For example,
var dataSet;
alert("Variable dataSet is : " + typeof dataSet);
Above code snippet will return the output like
variable dataSet is : undefined.
I use two different ways depending on the object.
if( !variable ){
// variable is either
// 1. '';
// 2. 0;
// 3. undefined;
// 4. null;
// 5. false;
}
Sometimes I do not want to evaluate an empty string as falsey, so then I use this case
function invalid( item ){
return (item === undefined || item === null);
}
if( invalid( variable )){
// only here if null or undefined;
}
If you need the opposite, then in the first instance !variable becomes !!variable, and in the invalid function === become != and the function names changes to notInvalid.
My preference is typeof(elem) != 'undefined' && elem != null.
However you choose, consider putting the check in a function like so
function existy (x) {
return typeof (x) != 'undefined' && x != null;
}
If you don't know the variable is declared then continue with typeof (x) != 'undefined' && x != null;
Where you know the variable is declared but may not be existy, you could use
existy(elem) && doSomething(elem);
The variable you are checking may be a nested property sometimes. You can use prop || {} to go down the line checking existance to the property in question:
var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;
After each property use (...' || {}').nextProp so that a missing property won't throw an error.
Or you could use existy like existy(o) && existy(o.p) && existy(o.p.q) && doSomething(o.p.q)
These answers (aside from the Fred Gandt solution ) are all either incorrect or incomplete.
Suppose I need my variableName; to carry an undefined value, and therefore it has been declared in a manner such as var variableName; which means it's already initialized; - How do I check if it's already declared?
Or even better - how do I immediately check if "Book1.chapter22.paragraph37" exists with a single call, but not rise a reference error?
We do it by using the most powerful JasvaScript operator, the in operator.:
"[variable||property]" in [context||root]
>> true||false
It depends on the situation. If you're checking for something that may or may not have been defined globally outside your code (like jQuery perhaps) you want:
if (typeof(jQuery) != "undefined")
(No need for strict equality there, typeof always returns a string.) But if you have arguments to a function that may or may not have been passed, they'll always be defined, but null if omitted.
function sayHello(name) {
if (name) return "Hello, " + name;
else return "Hello unknown person";
}
sayHello(); // => "Hello unknown person"
if (variable === undefined) {}
works just fine, and only checks for undefined.
You could use a try...catch block like the following:
var status = 'Variable exists'
try {
myVar
} catch (ReferenceError) {
status = 'Variable does not exist'
}
console.log(status)
A disadvantage is you cannot put it in a function as it would throw a ReferenceError
function variableExists(x) {
var status = true
try {
x
} catch (ReferenceError) {
status = false
}
return status
}
console.log(variableExists(x))
Edit:
If you were working in front-end Javascript and you needed to check if a variable was not initialized (var x = undefined would count as not initialized), you could use:
function globalVariableExists(variable) {
if (window[variable] != undefined) {
return true
}
return false
}
var x = undefined
console.log(globalVariableExists("x"))
console.log(globalVariableExists("y"))
var z = 123
console.log(globalVariableExists("z"))
Edit 2:
If you needed to check if a variable existed in the current scope, you could simply pass this to the function, along with the name of the variable contained in a string:
function variableExists(variable, thisObj) {
if (thisObj[variable] !== undefined) {
return true
}
return false
}
class someClass {
constructor(name) {
this.x = 99
this.y = 99
this.z = 99
this.v = 99
console.log(variableExists(name, this))
}
}
new someClass('x')
new someClass('y')
new someClass('z')
new someClass('v')
new someClass('doesNotExist')
I prefer this method for it's accuracy and succinctness:
var x
if (x === void 0) {
console.log(`x is undefined`)
} else {
console.log(`x is defined`)
}
As has been mentioned in other comments and answers, undefined isn't guaranteed to be undefined. Because it's not a keyword, it can be redefined as a variable in scopes other than the global scope. Here's little example that demonstrates this nuance:
var undefined = 'bar'
console.log(`In the global scope: ${undefined}`)
function foo() {
var undefined = 'defined'
var x
if (x === undefined) {
console.log(`x === undefined`)
} else {
console.log(`x !== undefined`)
}
if (x === void 0) {
console.log(`x === void 0`)
} else {
console.log(`x !== void 0`)
}
}
foo()
See void for compatibility (supported in IE5!?!! Wow!).
I'm surprised this wasn't mentioned yet...
here are a couple of additional variations using this['var_name']
the benefit of using this method that it can be used before a variable is defined.
if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part
// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!
In ReactJS, things are a bit more complicated! This is because it is a compiled environment, which follows ESLint's no-undef rule since react-scripts#2.0.3 (released Oct. 1st, 2018). The documentation here is helpful to anyone interested in this problem...
In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code....
This [new] rule [of ES6] will warn when it encounters a reference to an identifier that has not yet been declared.
So, while it's possible to have an undefined (or "uninitialized") variable, it is not possible to have an undeclared variable in ReactJS without turning off the eslint rules.
This can be very frustrating -- there are so many projects on GitHub that simply take advantage of the pre-ES6 standards; and directly compiling these without any adjustments is basically impossible.
But, for ReactJS, you can use eval(). If you have an undeclared variable like...
if(undeclaredvar) {...}
You can simply rewrite this part as...
if(eval('typeof undeclaredvar !== "undefined"')) {...}
For instance...
if(eval("false")) {
console.log("NO!");
}
if(eval("true")) {
console.log("YEAH!");
}
For those importing GitHub repositories into a ReactJS project, this is simply the only way to check if a variable is declared. Before closing, I'd like to remind you that there are security issues with eval() if use incorrectly.
For the if condition to work correctly, we have to use the keyword let for creating variables.
let name = undefined;
if (name) {
alert('valid')
};

JavaScript object detection

I am currently practicing javascript and I'm currently having trouble with object detection. I want to create an object and detect whether it exists. Below is some example code I am currently using.
The code sample below is how I am creating my object.
var obj = obj || {};
Should I be using this?
if (typeof obj !== "undefined") {
// code
}
Or this?
if (obj !== null) {
}
The value undefined means that the variable has not been assigned a value. The value null indicates that it has been assigned the value null. The === operator (and its negation, !==) prevent type coercion.
Which is right? It all depends on what you are trying to accomplish. Both undefined and null are "falsy" values, meaning that each one evaluates to false in a boolean context (as do false, 0, and the empty string).
Note that if obj is null, then typeof obj is not "undefined".
The usual practice is to use:
var obj = obj || {};
When that code runs, you can be certain that obj has been defined (because of the var declaration), though it may not have been assigned a value.
If the value of obj resolves to a "falsey" value, then you will assign a reference to a new object.
Possible outcomes are:
If obj has not been assigned a value, a new object reference is assigned.
If obj has previously been assigned a "falsey" value, it will be replaced by a new object reference (which may mess with whatever code assigned it the falsey value).
If obj has previously been assigned a "truethy" primitive value, the following assignments of properties to obj will throw an error and script execution will stop.
if obj is already a reference to an object other than null, then subsequent assignments of properties will be to that object. Depending on the type of object, things may be ok. Or not. Presumably something outside your control created the object and so may modify or destroy it without your knowledge. What will you do?
It is not possible in javascript to deal, in general, with cases 2 and 3, or 4 where it's not your obj you're dealiing with. So use a name that is unlikely to clash with any other and hope you get #1 or #4 and things go well.
Incidentally, code added after yours may still result (more or less) in #4, even if you had #1 at the point the code is executed.
There is no additional benefit to tests like:
if (typeof obj == 'undefined')
because the outcome is essentially the same.

Init object in javascript using || operator [duplicate]

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.
Sometimes I see in javascript code something like this:
var myObj = myObj || {};
So, what actually happen here? I suppose || operator returns true or false, but it's not correct.
The || operator returns the left operand if it evaluates as true, otherwise it evaluates and returns the right operand. In other words, a || b is equivalent to a ? a : b except that a is only evaluated once.
To understand the || operator, let's first look at a fairly basic example. The logical OR operator may be used to provide a default value for a defined variable as follows:
var bar = false,
foobar = 5,
foo = bar || foobar; // foo = 5
In this case, foo will only be assigned the value of foobar if bar is considered falsy. A falsy value could be considered being equal to 0, false, undefined, null, NaN or empty (e.g "").
This initializes myObj unless it is already defined.
You can use this construct to get the object that is not null, undefined, etc. This is used in cases where you use myObj later on in the code which requires it to be an object. If, for some reason, myObj is undefined prior to this line, re-assigning it leaves it undefined or null, in which case it would be assigned {}.
You can think of this as:
// If the object is already defined
if (myObj)
var myObj = myObj;
// It was undefined or null, so assign an empty object to it.
else
var myObj = {};
The OR op (||) will return the first non-empty/false parameter.
In the case specified, if myObj is false or null, it will be set to an empty object (the {} brackets are used to create objects)
|| is a short circuit operator. If the first operand evaluates to true the second is not evaluated.
Thus JS a || b is something like c# a ?? b
if myObj is undefined or null then it evaluates the expression on the right side of || which creates a new empty object
so myObj is either myObj if it is not null or an empty object if myObj is null
i hope you understand what i mean

JavaScript check if variable exists (is defined/initialized)

Which method of checking if a variable has been initialized is better/correct?
(Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
You want the typeof operator. Specifically:
if (typeof variable !== 'undefined') {
// the variable is defined
}
The typeof operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison === instead of simple equality ==, see:Which equals operator (== vs ===) should be used in JavaScript comparisons?
In many cases, using:
if (elem) { // or !elem
will do the job for you!... this will check these below cases:
undefined: if the value is not defined and it's undefined
null: if it's null, for example, if a DOM element not exists...
empty string: ''
0: number zero
NaN: not a number
false
So it will cover off kind of all cases, but there are always weird cases which we'd like to cover as well, for example, a string with spaces, like this ' ' one, this will be defined in javascript as it has spaces inside string... for example in this case you add one more check using trim(), like:
if(elem) {
if(typeof elem === 'string' && elem.trim()) {
///
Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object {} are always true.
I create the image below to show a quick brief of the answer:
In JavaScript, a variable can be defined, but hold the value undefined, so the most common answer is not technically correct, and instead performs the following:
if (typeof v === "undefined") {
// no variable "v" is defined in the current scope
// *or* some variable v exists and has been assigned the value undefined
} else {
// some variable (global or local) "v" is defined in the current scope
// *and* it contains a value other than undefined
}
That may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code's behavior and understand it yourself (if you care about such things):
if ("v" in window) {
// global variable v is defined
} else {
// global variable v is not defined
}
This, of course, assumes you are running in a browser (where window is a name for the global object). But if you're mucking around with globals like this you're probably in a browser. Subjectively, using 'name' in window is stylistically consistent with using window.name to refer to globals. Accessing globals as properties of window rather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.
In the majority of cases you would use:
elem != null
Unlike a simple if (elem), it allows 0, false, NaN and '', but rejects null or undefined, making it a good, general test for the presence of an argument, or property of an object.
The other checks are not incorrect either, they just have different uses:
if (elem): can be used if elem is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).
typeof elem == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property.
This is the only check that won't throw an error if elem is not declared (i.e. no var statement, not a property of window, or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.
Also useful is a strict comparison against undefined:
if (elem === undefined) ...
However, because the global undefined can be overridden with another value, it is best to declare the variable undefined in the current scope before using it:
var undefined; // really undefined
if (elem === undefined) ...
Or:
(function (undefined) {
if (elem === undefined) ...
})();
A secondary advantage of this method is that JS minifiers can reduce the undefined variable to a single character, saving you a few bytes every time.
Check if window.hasOwnProperty("varname")
An alternative to the plethora of typeof answers;
Global variables declared with a var varname = value; statement in the global scope
can be accessed as properties of the window object.
As such, the hasOwnProperty() method, which
returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it)
can be used to determine whether
a var of "varname" has been declared globally i.e. is a property of the window.
// Globally established, therefore, properties of window
var foo = "whatever", // string
bar = false, // bool
baz; // undefined
// window.qux does not exist
console.log( [
window.hasOwnProperty( "foo" ), // true
window.hasOwnProperty( "bar" ), // true
window.hasOwnProperty( "baz" ), // true
window.hasOwnProperty( "qux" ) // false
] );
What's great about hasOwnProperty() is that in calling it, we don't use a variable that might as yet be undeclared - which of course is half the problem in the first place.
Although not always the perfect or ideal solution, in certain circumstances, it's just the job!
Notes
The above is true when using var to define a variable, as opposed to let which:
declares a block scope local variable, optionally initializing it to a value.
is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
At the top level of programs and functions, let, unlike var, does not create a property on the global object.
For completeness: const constants are, by definition, not actually variable (although their content can be); more relevantly:
Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared.
The value of a constant cannot change through reassignment, and it can't be redeclared.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
Since let variables or const constants are never properties of any object which has inherited the hasOwnProperty() method, it cannot be used to check for their existence.
Regarding the availability and use of hasOwnProperty():
Every object descended from Object inherits the hasOwnProperty() method. [...] unlike the in operator, this method does not check down the object's prototype chain.
How to check if a variable exists
This is a pretty bulletproof solution for testing if a variable exists and has been initialized :
var setOrNot = typeof variable !== typeof undefined;
It is most commonly used in combination with a ternary operator to set a default in case a certain variable has not been initialized :
var dark = typeof darkColor !== typeof undefined ? darkColor : "black";
Problems with encapsulation
Unfortunately, you cannot simply encapsulate your check in a function.
You might think of doing something like this :
function isset(variable) {
return typeof variable !== typeof undefined;
}
However, this will produce a reference error if you're calling eg. isset(foo) and variable foo has not been defined, because you cannot pass along a non-existing variable to a function :
Uncaught ReferenceError: foo is not defined
Testing whether function parameters are undefined
While our isset function cannot be used to test whether a variable exists or not (for reasons explained hereabove), it does allow us to test whether the parameters of a function are undefined :
var a = '5';
var test = function(x, y) {
console.log(isset(x));
console.log(isset(y));
};
test(a);
// OUTPUT :
// ------------
// TRUE
// FALSE
Even though no value for y is passed along to function test, our isset function works perfectly in this context, because y is known in function test as an undefined value.
Short way to test a variable is not declared (not undefined) is
if (typeof variable === "undefined") {
...
}
I found it useful for detecting script running outside a browser (not having declared window variable).
There is another short hand way to check this, when you perform simple assignments and related checks. Simply use Conditional (Ternary) Operator.
var values = typeof variable !== 'undefined' ? variable : '';
Also this will be helpful, when you try to declare the Global variable with instance assignment of the reference variable.
If you wanted to check variable shouldn't be undefined or null. Then perform below check.
When the variable is declared, and if you want to check the value, this is even Simple: and it would perform undefined and null checks together.
var values = variable ? variable : '';
It depends if you just care that the variable has been defined or if you want it to have a meaningful value.
Checking if the type is undefined will check if the variable has been defined yet.
=== null or !== null will only check if the value of the variable is exactly null.
== null or != null will check if the value is undefined or null.
if(value) will check if the variable is undefined, null, 0, or an empty string.
Try-catch
If variable was not defined at all (for instance: external library which define global variable is not yet loaded - e.g. google maps), you can check this without break code execution using try-catch block as follows (you don't need to use strict mode)
try{
notDefinedVariable;
} catch(e) {
console.log('detected: variable not exists');
}
console.log('but the code is still executed');
notDefinedVariable; // without try-catch wrapper code stops here
console.log('code execution stops. You will NOT see this message on console');
BONUS: (referring to other answers) Why === is more clear than == (source)
if( a == b )
if( a === b )
The highest answer is correct, use typeof.
However, what I wanted to point out was that in JavaScript undefined is mutable (for some ungodly reason). So simply doing a check for varName !== undefined has the potential to not always return as you expect it to, because other libs could have changed undefined. A few answers (#skalee's, for one), seem to prefer not using typeof, and that could get one into trouble.
The "old" way to handle this was declaring undefined as a var to offset any potential muting/over-riding of undefined. However, the best way is still to use typeof because it will ignore any overriding of undefined from other code. Especially if you are writing code for use in the wild where who knows what else could be running on the page...
if (typeof console != "undefined") {
...
}
Or better
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
Works in all browsers
To contribute to the debate, if I know the variable should be a string or an object I always prefer if (!variable), so checking if its falsy. This can bring to more clean code so that, for example:
if (typeof data !== "undefined" && typeof data.url === "undefined") {
var message = 'Error receiving response';
if (typeof data.error !== "undefined") {
message = data.error;
} else if (typeof data.message !== "undefined") {
message = data.message;
}
alert(message);
}
..could be reduced to:
if (data && !data.url) {
var message = data.error || data.message || 'Error receiving response';
alert(message)
}
To check if a variable has been declared/set I did this dirty trick.
I haven't found a way to extract the code to a function, even with eval. Se this comment below for an explanation about why.
"use strict";
// var someVar;
var declared;
try {
someVar;
declared = true;
} catch(e) {
declared = false;
}
if (declared) {
console.log("someVar is declared; now has the value: " + someVar);
} else {
console.log("someVar is not declared");
}
The most robust 'is it defined' check is with typeof
if (typeof elem === 'undefined')
If you are just checking for a defined variable to assign a default, for an easy to read one liner
you can often do this:
elem = elem || defaultElem;
It's often fine to use, see: Idiomatic way to set default value in javascript
There is also this one liner using the typeof keyword:
elem = (typeof elem === 'undefined') ? defaultElem : elem;
Null is a value in JavaScript and typeof null returns "object"
Therefore, accepted answer will not work if you pass null values. If you pass null values, you need to add an extra check for null values:
if ((typeof variable !== "undefined") && (variable !== null))
{
// the variable is defined and not null
}
In the particular situation outlined in the question,
typeof window.console === "undefined"
is identical to
window.console === undefined
I prefer the latter since it's shorter.
Please note that we look up for console only in global scope (which is a window object in all browsers). In this particular situation it's desirable. We don't want console defined elsewhere.
#BrianKelley in his great answer explains technical details. I've only added lacking conclusion and digested it into something easier to read.
It is difficult to distinguish between undefined and null. Null is a value you can assign to a variable when you want to indicate that the variable has no particular value. Undefined
is a special value which will be the default value of unassigned variables.
var _undefined;
var _null = null;
alert(_undefined);
alert(_null);
alert(_undefined == _null);
alert(_undefined === _null);
you can use the typeof operator.
For example,
var dataSet;
alert("Variable dataSet is : " + typeof dataSet);
Above code snippet will return the output like
variable dataSet is : undefined.
I use two different ways depending on the object.
if( !variable ){
// variable is either
// 1. '';
// 2. 0;
// 3. undefined;
// 4. null;
// 5. false;
}
Sometimes I do not want to evaluate an empty string as falsey, so then I use this case
function invalid( item ){
return (item === undefined || item === null);
}
if( invalid( variable )){
// only here if null or undefined;
}
If you need the opposite, then in the first instance !variable becomes !!variable, and in the invalid function === become != and the function names changes to notInvalid.
My preference is typeof(elem) != 'undefined' && elem != null.
However you choose, consider putting the check in a function like so
function existy (x) {
return typeof (x) != 'undefined' && x != null;
}
If you don't know the variable is declared then continue with typeof (x) != 'undefined' && x != null;
Where you know the variable is declared but may not be existy, you could use
existy(elem) && doSomething(elem);
The variable you are checking may be a nested property sometimes. You can use prop || {} to go down the line checking existance to the property in question:
var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;
After each property use (...' || {}').nextProp so that a missing property won't throw an error.
Or you could use existy like existy(o) && existy(o.p) && existy(o.p.q) && doSomething(o.p.q)
These answers (aside from the Fred Gandt solution ) are all either incorrect or incomplete.
Suppose I need my variableName; to carry an undefined value, and therefore it has been declared in a manner such as var variableName; which means it's already initialized; - How do I check if it's already declared?
Or even better - how do I immediately check if "Book1.chapter22.paragraph37" exists with a single call, but not rise a reference error?
We do it by using the most powerful JasvaScript operator, the in operator.:
"[variable||property]" in [context||root]
>> true||false
It depends on the situation. If you're checking for something that may or may not have been defined globally outside your code (like jQuery perhaps) you want:
if (typeof(jQuery) != "undefined")
(No need for strict equality there, typeof always returns a string.) But if you have arguments to a function that may or may not have been passed, they'll always be defined, but null if omitted.
function sayHello(name) {
if (name) return "Hello, " + name;
else return "Hello unknown person";
}
sayHello(); // => "Hello unknown person"
if (variable === undefined) {}
works just fine, and only checks for undefined.
You could use a try...catch block like the following:
var status = 'Variable exists'
try {
myVar
} catch (ReferenceError) {
status = 'Variable does not exist'
}
console.log(status)
A disadvantage is you cannot put it in a function as it would throw a ReferenceError
function variableExists(x) {
var status = true
try {
x
} catch (ReferenceError) {
status = false
}
return status
}
console.log(variableExists(x))
Edit:
If you were working in front-end Javascript and you needed to check if a variable was not initialized (var x = undefined would count as not initialized), you could use:
function globalVariableExists(variable) {
if (window[variable] != undefined) {
return true
}
return false
}
var x = undefined
console.log(globalVariableExists("x"))
console.log(globalVariableExists("y"))
var z = 123
console.log(globalVariableExists("z"))
Edit 2:
If you needed to check if a variable existed in the current scope, you could simply pass this to the function, along with the name of the variable contained in a string:
function variableExists(variable, thisObj) {
if (thisObj[variable] !== undefined) {
return true
}
return false
}
class someClass {
constructor(name) {
this.x = 99
this.y = 99
this.z = 99
this.v = 99
console.log(variableExists(name, this))
}
}
new someClass('x')
new someClass('y')
new someClass('z')
new someClass('v')
new someClass('doesNotExist')
I prefer this method for it's accuracy and succinctness:
var x
if (x === void 0) {
console.log(`x is undefined`)
} else {
console.log(`x is defined`)
}
As has been mentioned in other comments and answers, undefined isn't guaranteed to be undefined. Because it's not a keyword, it can be redefined as a variable in scopes other than the global scope. Here's little example that demonstrates this nuance:
var undefined = 'bar'
console.log(`In the global scope: ${undefined}`)
function foo() {
var undefined = 'defined'
var x
if (x === undefined) {
console.log(`x === undefined`)
} else {
console.log(`x !== undefined`)
}
if (x === void 0) {
console.log(`x === void 0`)
} else {
console.log(`x !== void 0`)
}
}
foo()
See void for compatibility (supported in IE5!?!! Wow!).
I'm surprised this wasn't mentioned yet...
here are a couple of additional variations using this['var_name']
the benefit of using this method that it can be used before a variable is defined.
if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part
// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!
In ReactJS, things are a bit more complicated! This is because it is a compiled environment, which follows ESLint's no-undef rule since react-scripts#2.0.3 (released Oct. 1st, 2018). The documentation here is helpful to anyone interested in this problem...
In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code....
This [new] rule [of ES6] will warn when it encounters a reference to an identifier that has not yet been declared.
So, while it's possible to have an undefined (or "uninitialized") variable, it is not possible to have an undeclared variable in ReactJS without turning off the eslint rules.
This can be very frustrating -- there are so many projects on GitHub that simply take advantage of the pre-ES6 standards; and directly compiling these without any adjustments is basically impossible.
But, for ReactJS, you can use eval(). If you have an undeclared variable like...
if(undeclaredvar) {...}
You can simply rewrite this part as...
if(eval('typeof undeclaredvar !== "undefined"')) {...}
For instance...
if(eval("false")) {
console.log("NO!");
}
if(eval("true")) {
console.log("YEAH!");
}
For those importing GitHub repositories into a ReactJS project, this is simply the only way to check if a variable is declared. Before closing, I'd like to remind you that there are security issues with eval() if use incorrectly.
For the if condition to work correctly, we have to use the keyword let for creating variables.
let name = undefined;
if (name) {
alert('valid')
};

Categories

Resources