Check if value is assigned [duplicate] - javascript

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')
};

Related

Javascript typeof of undefined objects subproperty

Let's say I would like to check if a property to the object Foo is defined or not, I would use in this scenario:
typeof Foo.property != 'undefined'
But if not only the property does not exists, but also the object is undefined, this results in an error.
Is there any single line way to check if an objects property is defined, and return false in the following cases:
if the object property is not defined
if the object is not defined
WHY I WANT THIS: I am writing a script in NodeJS, which uses a class, which would be used in the front end also, and instead of maintaining two different files, which would end up being basically the same except for minor changes for the two environments, I would like to differentiate between the environments with some basic IF logic.
OTHER POSSIBLE USE CASES: Let's say we have the following object:
function Foo() {
this.case1={
info1: 'something',
info2: 'something',
.....
info1000: 'something'
}
this.case2={
info1: 'something',
info2: 'something',
......
info1000: 'something'
}
}
If I would like to decide which case applies to me, and the decision lies in one of the inner info's, I would first have to check if the respective case exists, and then if the respective info exists(2 conditions):
if (typeof Foo.case1 != 'undefined') && (typeof Foo.case1.info1 != 'undefined')
If this is a much deeper nested object, there would be a lot of condition checking and typing, to get some basic information: if case1 does not exist at all, then I will use case2.
You could use an and (&&) clause.
typeof Foo !== 'undefined' && typeof Foo.property !== 'undefined'
Or put more simply:
Foo !== undefined && Foo.property !== undefined
Edit: As David Titarenco pointed out, this works due to something known as short-circuit evaluation. That basically means that if the first part evaluates to false (Foo !== undefined) then the second part is never evaluated.
The simplest answer that comes to mind is this. It is not as 100%-strict as yours, but it would take a very unusual situation to break it:
if (Foo && 'property' in Foo) {
The Foo object is evaluated as boolean. A null or undefined type will be false, any object will be true. We also check the "key" side of the key/value pair, rather than the value. It is technically possible to have the key property, but for it to have the actual value undefined. This will return false in that case.
The one caveat: If Foo is another value type: true, 12, function()..., then the first condition may pass (but I don't believe the second one will)
Okay, I came up with a small function, which on initial testing does what I wanted, but I've only tested it for like 5 minutes, so there could be errors in it, if yes, please point it out:
function isDefined(path, namespace) {
if (typeof namespace == 'undefined') {
namespace=global;
// global is the default namespace for NodeJS,
// change this to window if you use it in a browser
}
path=path.split(".");
for (var i=0;i<path.length ;i++)
{
if (typeof namespace[path[i]] == 'undefined') return false;
else namespace=namespace[path[i]];
}
return true;
}
Usage: if you would want to test for example if Test.Test1.Test2.Test3.Test4.Test5.Test6 is defined you can use it like this:
if (isDefined('Test.Test1.Test2.Test3.Test4.Test5.Test6')===true) {
//it is defined
}

Javascript unassigned var? [duplicate]

This question already has answers here:
Effect of declared and undeclared variables
(4 answers)
Closed 8 years ago.
What happens to a variable declared in Javascript, if no initial value was assigned to it?
Let's suppose that I declare the variable as below
var cancel;
Now, does this variable "cancel" has a value or is it null or what?
Thanks.
undefined is a property of the global object, i.e. it is a variable in global scope. The initial value of undefined is the primitive value undefined.
In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.
A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.
Since undefined is not a reserved word, it can be used as an identifier (variable name) in any scope other than the global scope.
Example
var x;
if (x === undefined) {
// these statements execute
}
else {
// these statements do not execute
}
typeof operator
Alternatively, typeof can be used:
var x;
if (typeof x === 'undefined') {
// these statements execute
}
One reason to use typeof is that it does not throw an error if the variable has not been defined.
// x has not been defined before
if (typeof x === 'undefined') { // evaluates to true without errors
// these statements execute
}
if(x === undefined){ // throws a ReferenceError
}
void operator
The void operator is a third alternative.
var x;
if (x === void 0) {
// these statements execute
}
// y has not been defined before
if (y === void 0) {
// throws a ReferenceError (in contrast to `typeof`)
}
Source: MDN - Mozilla Developer Network
If you just execute the following you will see the alert box with undefined value. Just try yourself in Firebug or chrome developer tool
var cancel;
alert(cancel)
Undeclared variables or variables without a value have a type of 'undefined'.
It's important to note that unlike some other languages (like PHP, for example) 'undefined' is a Javascript keyword that can be checked against, for example:
if(cancel == undefined) { alert('Cancel is undefined!'); };
You can check for the type of a Javascript variable using the javascript
typeof
command, for example:
var cancel;
var typeOfCancel = typeof cancel; // In this case, undefined
var cancel = true;
var typeOfCancel = typeof cancel; // In this case, boolean
This can lead to an extra check, when working with javascript, to see if a variable has been set, as in:
if(cancel == undefined || cancel == null || cancel == '') {
// React to the empty value here
}
You can see this working here:
http://jsfiddle.net/7bu84/

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')
};

variable === undefined vs. typeof variable === "undefined"

The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.
Global Variables: typeof variable === "undefined"
Local Variables: variable === undefined
Properties: object.prop === undefined
Why does jQuery use one approach for global variables and another for locals and properties?
For undeclared variables, typeof foo will return the string literal "undefined", whereas the identity check foo === undefined would trigger the error "foo is not defined".
For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.
I'd stick to using typeof foo === "undefined" everywhere. That can never go wrong.
I imagine the reason why jQuery recommends the two different methods is that they define their own undefined variable within the function that jQuery code lives in, so within that function undefined is safe from tampering from outside. I would also imagine that someone somewhere has benchmarked the two different approaches and discovered that foo === undefined is faster and therefore decided it's the way to go. [UPDATE: as noted in the comments, the comparison with undefined is also slightly shorter, which could be a consideration.] However, the gain in practical situations will be utterly insignificant: this check will never, ever be any kind of bottleneck, and what you lose is significant: evaluating a property of a host object for comparison can throw an error whereas a typeof check never will.
For example, the following is used in IE for parsing XML:
var x = new ActiveXObject("Microsoft.XMLDOM");
To check whether it has a loadXML method safely:
typeof x.loadXML === "undefined"; // Returns false
On the other hand:
x.loadXML === undefined; // Throws an error
UPDATE
Another advantage of the typeof check that I forgot to mention was that it also works with undeclared variables, which the foo === undefined check does not, and in fact throws a ReferenceError. Thanks to #LinusKleen for reminding me. For example:
typeof someUndeclaredVariable; // "undefined"
someUndeclaredVariable === undefined; // throws a ReferenceError
Bottom line: always use the typeof check.
Yet another reason for using the typeof-variant: undefined can be redefined.
undefined = "foo";
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
The result of typeof variable cannot.
Update: note that this is not the case in ES5 there the global undefined is a non-configurable, non-writable property:
15.1.1 Value Properties of the Global Object
[...]
15.1.1.3 undefined
The value of undefined is undefined (see 8.1). This property has the attributes
{ [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
But it still can be shadowed by a local variable:
(function() {
var undefined = "foo";
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
})()
or parameter:
(function(undefined) {
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
})("foo")
Who is interested in the performance gain of variable === undefined, may take a look here, but it seems to be a chrome optimization only.
http://jsperf.com/type-of-undefined-vs-undefined/30
http://jsperf.com/type-of-undefined-vs-undefined
Because undefined is not always declared, but jQuery declares undefined in its main function. So they use the safe undefined value internally, but outside, they use the typeof style to be safe.
For local variables, checking with localVar === undefined will work because they must have been defined somewhere within the local scope or they will not be considered local.
For variables which are not local and not defined anywhere, the check someVar === undefined will throw exception: Uncaught ReferenceError: j is not defined
Here is some code which will clarify what I am saying above. Please pay attention to inline comments for further clarity.
function f (x) {
if (x === undefined) console.log('x is undefined [x === undefined].');
else console.log('x is not undefined [x === undefined.]');
if (typeof(x) === 'undefined') console.log('x is undefined [typeof(x) === \'undefined\'].');
else console.log('x is not undefined [typeof(x) === \'undefined\'].');
// This will throw exception because what the hell is j? It is nowhere to be found.
try
{
if (j === undefined) console.log('j is undefined [j === undefined].');
else console.log('j is not undefined [j === undefined].');
}
catch(e){console.log('Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.');}
// However this will not throw exception
if (typeof j === 'undefined') console.log('j is undefined (typeof(x) === \'undefined\'). We can use this check even though j is nowhere to be found in our source code and it will not throw.');
else console.log('j is not undefined [typeof(x) === \'undefined\'].');
};
If we call the above code like this:
f();
The output would be this:
x is undefined [x === undefined].
x is undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
If we call the above code like these (with any value actually):
f(null);
f(1);
The output will be:
x is not undefined [x === undefined].
x is not undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
When you do the check like this: typeof x === 'undefined', you are essentially asking this: Please check if the variable x exists (has been defined) somewhere in the source code. (more or less). If you know C# or Java, this type of check is never done because if it does not exist, it will not compile.
<== Fiddle Me ==>
Summary:
When at global scope we actually want to return true if the variable is not declared or has the value undefined:
var globalVar1;
// This variable is declared, but not defined and thus has the value undefined
console.log(globalVar1 === undefined);
// This variable is not declared and thus will throw a referenceError
console.log(globalVar2 === undefined);
Because in global scope we are not 100% sure if a variable is declared this might give us a referenceError. When we use the typeof operator on the unknown variable we are not getting this issue when the variable is not declared:
var globalVar1;
console.log(typeof globalVar1 === 'undefined');
console.log(typeof globalVar2 === 'undefined');
This is due to the fact that the typeof operator returns the string undefined when a variable is not declared or currently hold the value undefined which is exactly what we want.
With local variables we don't have this problem because we know beforehand that this variable will exist. We can simply look in the respective function if the variable is present.
With object properties we don't have this problem because when we try to lookup an object property which does not exist we also get the value undefined
var obj = {};
console.log(obj.myProp === undefined);
jQuery probably expects you to be using let and const variables in functions going forward, which in JavaScript's ES6 2015 design do NOT allow you to use any local scope (function) let or const variables until they are declared. Even hoisting by Javascript does not allow you to even type-check them!
If you try and do that, JavaScript generates an error, unlike with var variables which when hoisted creates a declared but uninitialized variable you can type check or check to see if its undefined.
If you declare a let or const variable in a function, but AFTER trying to access it, typeof checks still create a Reference Error in JavaScript! Its very odd behavior, and illogical to me why it was designed that way. But that is why jQuery likely sees no use for typeof function variable use. Example:
function MyError(){
// WOW! This variable DOES NOT EVEN EXIST, but you can still check its type!
if(typeof x === 'undefined')
{
alert(1);// OK!
}
// ERROR!
// WOW! You cannot even check an existing "let" variable's TYPE in a local function!
if(typeof y === 'undefined')//REFERENCE ERROR!!
{
alert(2);
}
// We defined the variable so its hoisted to the top but in a dead zone
let y = 'test';
}
MyError();
// RESULT
// alert 1 fires but a REFERENCE ERROR is generated from the second alert 2 condition.
It is odd above how a non-existing local variable cant be checked using typeof for 'undefined', but a declared let variable in the function cannot! So this is likely why I would not depend on jQuery to define what is best. There are edge cases.
More Weirdness on "undefined" variables in JavaScript
**undefined has two different expressions, and three different uses, as follows:
"typeof" and "undefined" types : Variables that are not declared and do not exist are not assigned anything, but have a "type" of undefined. If you access a variable that does NOT even exist, much less declared or initialized, you will generate a REFERENCE ERROR if you access it, even when testing for the primitive default value of undefined which is assigned to declared variables until assigned a value. So checking the "typeof" prevents this error in this one case as follows:
// In this first test, the variable "myVariable1" does not exist yet so creates
// an error if we try and check if its assigned the default value of undefined!
if (myVariable1 === undefined) alert(true);// REFERENCE ERROR!
// Here we can elegantly catch the "undefined" type
// of the missing variable and stop the REFERENCE ERROR using "typeof".
if (typeof myVariable1 === "undefined") alert(true);// true
// Here we have declared the missing variable and notice its
// still an "undefined" type until initialized with a value.
let myVariable1;
if (typeof myVariable1 === "undefined") alert(true);// true
// Lastly, after we assign a value, the type is no longer
// "undefined" so returns false.
myVariable1 = 'hello';
if (typeof myVariable1 === "undefined") alert(true);// false
All objects and types in JavaScript that are accessed but not declared will default to a type of "undefined". So, the lesson here is try and check for the typeof first, to prevent missing variable errors!
undefined primitive values : All declared variables not yet assigned a value are assigned in JavaScript the primitve of undefined. If you have declared a variable, but not initialized it yet, its assigned this default primitive type of undefined. That is not same as an "undefined" type. The primitive value of undefined is a reserved value but can be altered, but that's not what is asked here. Notice this catches all declared but uninitialized variables only:
let myVariable3;
if (myVariable3 === undefined) alert(true);// true
let myVariable4 = 'hello';
if (myVariable4 === undefined) alert(true);// false
Objects and undefined primitives : Lastly, Object properties do NOT behave like variables in JavaScript. Object properties, when missing do not become undefined types, but are simply assigned the primitive undefined as above for undeclared variables. So they act like #2:
let myObject = {};
if (myObject.myProperty === undefined) alert(true);// true
BEST PRACTICE
Lastly....this is a VERY GOOD REASON to always check for BOTH the "undefined" type and the undefined primitive value on variables in all your JavaScript code. Most will say, you will rarely need both. There may come a day when a missing variable is accessed in a library that does not exist and creates a nasty JavaScript REFERENCE ERROR! So I always do this check, and in this order, to stop all errors in JavaScript:
if (typeof myVariable !== "undefined" && myVariable !== undefined) {
// do something safe with myVariable!
}
typeof a === 'undefined' is faster then a === 'undefined' by about 2 times on node v6.9.1.

Checking for null/undefined in JavaScript

Can this code
if (typeof foo != "undefined" && foo !== null) { }
be safely refactored into this code?
if (foo != null) { }
Is it the exact same thing? (And if not, how is it different?)
Not really. You'll get thrown a ReferenceError exception in your second example if foo has not been declared.
On the other hand, you can safely check for undefined non-declared variables with the typeof operator.
A simple experiment will answer this question:
if( foo != null ) {
alert('foo not null');
}
the above example yields a javascript error in many browsers: "ReferenceError: Can't find variable: foo". This is because we've used a variable that has not been previously declared as an argument or var in current scope.
the typeof operator, on the other hand, makes an explicit accommodation for variables that haven't been defined -- it returns 'undefined', so:
if( typeof foo != 'undefined') {
alert('foo is not defined');
}
works as expected.
So the answer is "no" -- they are not the same thing -- though in some javascript environments they may behave the same way, in other environments your second form will produce errors when foo is not defined.
Variables can actually hold the value undefined, which is the default value if a variable has never been assigned to. So foo != null will work if your variable is declared using var or given a value through assignment, but if it isn't, you will get a ReferenceError. Therefore, the two snippets are not equivalent.
If you can be sure that foo is declared, this is safe and easier to understand than your original second snippet, assuming that nowhere in the code something like undefined = 42 exists:
if(foo !== undefined && foo !== null) { }

Categories

Resources