Checking if a variable exists in javascript - javascript

I know there are two methods to determine if a variable exists and not null(false, empty) in javascript:
1) if ( typeof variableName !== 'undefined' && variableName )
2) if ( window.variableName )
which one is more preferred and why?

A variable is declared if accessing the variable name will not produce a ReferenceError. The expression typeof variableName !== 'undefined' will be false in only one of two cases:
the variable is not declared (i.e., there is no var variableName in scope), or
the variable is declared and its value is undefined (i.e., the variable's value is not defined)
Otherwise, the comparison evaluates to true.
If you really want to test if a variable is declared or not, you'll need to catch any ReferenceError produced by attempts to reference it:
var barIsDeclared = true;
try{ bar; }
catch(e) {
if(e.name == "ReferenceError") {
barIsDeclared = false;
}
}
If you merely want to test if a declared variable's value is neither undefined nor null, you can simply test for it:
if (variableName !== undefined && variableName !== null) { ... }
Or equivalently, with a non-strict equality check against null:
if (variableName != null) { ... }
Both your second example and your right-hand expression in the && operation tests if the value is "falsey", i.e., if it coerces to false in a boolean context. Such values include null, false, 0, and the empty string, not all of which you may want to discard.

It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,
if (window.variableName)
is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.
That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.
if ( variableName && typeof variableName !== 'undefined' )

If you want to check if a variable (say v) has been defined and is not null:
if (typeof v !== 'undefined' && v !== null) {
// Do some operation
}
If you want to check for all falsy values such as: undefined, null, '', 0, false:
if (v) {
// Do some operation
}

I'm writing an answer only because I do not have enough reputations to comment the accepted answer from apsillers.
I agree with his answer, but
If you really want to test if a variable is undeclared, you'll need to
catch the ReferenceError ...
is not the only way. One can do just:
this.hasOwnProperty("bar")
to check if there is a variable bar declared in the current context.
(I'm not sure, but calling the hasOwnProperty could also be more fast/effective than raising an exception)
This works only for the current context (not for the whole current scope).

if ( typeof variableName !== 'undefined' && variableName )
//// could throw an error if var doesnt exist at all
if ( window.variableName )
//// could be true if var == 0
////further on it depends on what is stored into that var
// if you expect an object to be stored in that var maybe
if ( !!window.variableName )
//could be the right way
best way => see what works for your case

I found this shorter and much better:
if(varName !== (undefined || null)) { //do something }

if (variable) can be used if variable is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).
typeof variable == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property. This check will not throw and error is variable is not declared.

You can simply do
if(variableName){console.log("Variable exist")}

Related

Handling undefined variables simple conditions in NodeJS

Given this function:
var test = function(param1, param2_maybe_not_set) {
var my_object = {};
// code here...
}
What's the best, in your opinion?
my_object.new_key = (param2_maybe_not_set === undefined) ? null : param2_maybe_not_set;
OR
my_object.new_key = (param2_maybe_not_set === void 0) ? null : param2_maybe_not_set;
OR
my_object.new_key = (typeof param2_maybe_not_set === 'undefined') ? null : param2_maybe_not_set;
Alternatively, would this shortened expression be correct?
my_object.new_key = param2_maybe_not_set || null;
All four methods work (in the NodeJS console at least). Also jsPerf doesn't show a big gap between any of these (http://jsperf.com/typeof-performance/8)
Which one should be used, as a good practice?
They are not strictly equivalent, but can often be used interchangeably. Here are the major differences between them:
x === undefined: this performs a strict-equality comparison between the value and undefined, meaning that only a actual value of undefined will be true, whereas similar values like null or 0 will be false.
In the case of a function call, this check does not differentiate between f(a) and f(a, undefined) (in fact, none of the examples will; to differentiate, you'll have to look at arguments).
x === void 0: this uses the void keyword, which evaluates any expression and returns undefined. This was mostly done in the olden days to prevent surprises from people redefining the global undefined variable, but is not so useful nowadays (ECMAScript 5 mandates that undefined be read-only)
typeof x === 'undefined': this uses the typeof keyword, which has a unique ability - namely, that the operand is unevaluated. This means that something like typeof foobarbaz returns 'undefined' even if no such variable foobarbaz exists at all. Contrast this with foobarbaz === undefined, which will throw a ReferenceError if the variable name has never been declared.
x || null: this is the simplest and probably most readable alternative. The || operator is often used to "set defaults" on arguments, and can be chained like x || y || z || null.
In most cases, this is the idiomatic technique used. However, note that || performs implicit conversions, which means that any "falsy" values will trigger the next value (meaning that it can't differentiate between undefined, false, null, 0, '', and NaN). So, if your function expects to receive falsy values as arguments, it may be more prudent to explicitly check for undefined.
The option chosen to be an idiom in Javascript development to force a value for an unspecified argument is actually the last:
my_object.new_key = param2_maybe_not_set || null;
So this one should be preferrable since a lot of Javascript developers will immediately get its purpose.
Best.

Set JavaScript variable = null, or leave undefined?

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

Is there a nice simple way to check if a variable in Javascript has a value?

I want to check this:
if ( typeof myVar != "undefined" && myVar != null )
...
In other words, I want to check if a variable has a defined value (including 0 or an empty string), but not undefined or null, which I interpret as valueless.
Do I have to do the two-part check each time or is there a handy shortcut?
If you want to allow 0 and "" as valid values and you want to cover the case of the variable might not even be delcared, but don't consider null a valid value, then you have to specifically check for undefined and null like this:
if (typeof myVar !== 'undefined' && myVar !== null)
...
A lot of values are falsey (they don't satisfy if (myVar) so you really have to conciously decide which ones you're testing for. All of these are falsey:
undefined
false
0
""
null
NaN
If you want to allow some, but not others, then you have to do a more specific test than if (myVar) like I've shown above to isolate just the values you care about.
Here's a good writeup on falsey values: http://www.sitepoint.com/javascript-truthy-falsy/.
If you know the variable has been declared and you just want to see if it's been initialized with something other than null, you can use this:
if (myVar != undefined)
...
Using only the != instead of !== allows this to test for both undefined and null via type conversion. Although, I wouldn't recommend this because if you're trying to discern between falsey values, it's probably better to NOT let the JS engine do any type conversions at all so you can control exactly what it does without having to memorize all the type conversion equality rules. I'd stick with this to be more explicit:
if (typeof myVar !== 'undefined' && myVar !== null)
...
If you want to know if it has any non-falsey value, you can of course do this (but that won't allow 0 or "" as valid values:
if (myVar)
...
The 2-part method. If you don't check for the typeof first, you'll end up with a reference error.
If you know the context of myVar, you should be able to do this:
if (this.myVar != null) {
...
}
if myvar could be undefined, calling it without the typeof check will throw an error.
And if it is defined as null (like myvar= element.lastChild for an element with no children) you will miss catching it if you just use typeof.
Well, null is a defined value... so if you want to make sure that the variable doesn't contain null, and isn't undefined you must do both checks.

Javascript undefined condition

Could somebody explain to me the difference between if(obj.x == undefined) and if(typeof obj.x == 'undefined')
In some context the first one works fine, but in other I need to use the second way.
Questions
1 - What is the difference between the two condition?
2 - Is there a best practice?
The best practice is to not just check the truthiness but the strict equality
example
if (obj.x === undefined) {}
this use to be an issue because undefined (a global property) use to be writable, as of 1.8.5 is is non-writable, providing you with a secure comparison in ES5 spec environments.
per MDN
The two would usually be equivalent if you replaced the equality operator == with the strict equality operator ===. So obj.x === undefined and typeof obj.x == "undefined" are usually equivalent.
However, in pre-ECMAScript 5 environments (which still acount for the majority of web requests, in general), undefined is a writable property of the global object, meaning that undefined may be used as variable name or the global property may be assigned a different value. ECMAScript 5 makes the global property read-only, but even then, undefined may still be used as variable name within a function, meaning that the typeof check is always safer.
One further point in favour of typeof is that it may be used to check for a variable that may not have been declared whereas a direct comparison will throw a ReferenceError if the variable has not been declared. For example:
typeof foo == "undefined" // true
foo === undefined // ReferenceError
However, this is an unusual and not generally helpful thing to be doing.
The two are not equivalent tests because of the quite convoluted handling of special values by javascript. In the specific
undefined == null
is true, but typeof undefined is "undefined" while typeof null is "object".
The rules for those special values are quite complex and IMO illogical, so I think there's no "general rule". What you may find are common forms, for example
var value = obj.x || default_value;
that can be used if you're sure that obj will never be undefined or null (because in that case an exception would be thrown) and assuming that 0, NaN or an empty string should be considered as if no value was provided (because they're all "logically false" values). An empty array or an empty javascript object instead are considered "logically true".
Why is it that way? Why does (null).x throw an exception when null according to typeof is apparently an object and searching for a non-existent field in an object normally returns undefined instead?
I've no idea.
I never tried to find a logic in all those strange rules. I'm not actually even 100% sure there's one.
My suggestion is just to study and experiment with them.
second is easier and faster than first. First requires additional setup, definition of undefined and check wheter obj contains x as a property or method. second makes the check whether obj.x has been whenever defined and assigned
PS.: undefined will be evaluated to null so
obj.x == undefined is equivalent to obj.x == null
the best way to test for conditionality isusing obj.x this checks for both null-ability and undefined .
Thus
if(!obj.x)
{
alert(obj.x);
}
else
{
alert("obj.x is null or undefined"); //obj.x is null or undefined or any false value which is what you want. like obj.x is false or 0
}
The main difference of these two condition is typeof
The typeof operator is used to get the data type (returns a string) of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. The operator returns the data type.
if (typeof obj.x === 'undefined') {
txt = "x is undefined";
} else {
txt = "x is defined";
}

When to check for undefined and when to check for null

[Bounty Edit]
I'm looking for a good explanation when you should set/use null or undefined and where you need to check for it. Basically what are common practices for these two and is really possible to treat them separately in generic maintainable codee?
When can I safely check for === null, safely check for === undefined and when do I need to check for both with == null
When should you use the keyword undefined and when should one use the keyword null
I have various checks in the format of
if (someObj == null) or if (someObj != null) which check for both null and undefined. I would like to change all these to either === undefined or === null but I'm not sure how to guarantee that it will only ever be one of the two but not both.
Where should you use checks for null and where should you use checks for undefined
A concrete example:
var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
for (var i = 0; i < List.length; i++) {
if (List[i] == null) continue;
if (id === List[i].getId()) {
return List[i];
}
}
return null;
}
var deleteObject = function(id) {
var index = getIndex(id) // pretty obvouis function
// List[index] = null; // should I set it to null?
delete List[index]; // should I set it to undefined?
}
This is just one example of where I can use both null or undefined and I don't know which is correct.
Are there any cases where you must check for both null and undefined because you have no choice?
Functions implicitly return undefined. Undefined keys in arrays are undefined. Undefined attributes in objects are undefined.
function foo () {
};
var bar = [];
var baz = {};
//foo() === undefined && bar[100] === undefined && baz.something === undefined
document.getElementById returns null if no elements are found.
var el = document.getElementById("foo");
// el === null || el instanceof HTMLElement
You should never have to check for undefined or null (unless you're aggregating data from both a source that may return null, and a source which may return undefined).
I recommend you avoid null; use undefined.
Some DOM methods return null. All properties of an object that have not been set return undefined when you attempt to access them, including properties of an Array. A function with no return statement implicitly returns undefined.
I would suggest making sure you know exactly what values are possible for the variable or property you're testing and testing for these values explicitly and with confidence. For testing null, use foo === null. For testing for undefined, I would recommend using typeof foo == "undefined" in most situations, because undefined (unlike null) is not a reserved word and is instead a simple property of the global object that may be altered, and also for other reasons I wrote about recently here: variable === undefined vs. typeof variable === "undefined"
The difference between null and undefined is that null is itself a value and has to be assigned. It's not the default. A brand new variable with no value assigned to it is undefined.
var x;
// value undefined - NOT null.
x = null;
// value null - NOT undefined.
I think it's interesting to note that, when Windows was first written, it didn't do a lot of checks for invalid/NULL pointers. Afterall, no programmer would be dumb enough to pass NULL where a valid string was needed. And testing for NULL just makes the code larger and slower.
The result was that many UAEs were due to errors in client programs, but all the heat went to Microsoft. Since then, Microsoft has changed Windows to pretty much check every argument for NULL.
I think the lesson is that, unless you are really sure an argument will always be valid, it's probably worth verifying that it is. Of course, Windows is used by a lot of programmers while your function may only be used by you. So that certainly factors in regarding how likely an invalid argument is.
In languages like C and C++, you can use ASSERTs and I use them ALL the time when using these languages. These are statements that verify certain conditions that you never expect to happen. During debugging, you can test that, in fact, they never do. Then when you do a release build these statements are not included in the compiled code. In some ways, this seems like the best of both worlds to me.
If you call a function with no explicit return then it implicitly returns undefined. So if I have a function that needs to say that it did its task and there is nothing result, e.g. a XMLHTTPRequest that returned nothing when you normally expect that there would be something (like a database call), then I would explicitly return null.
Undefined is different from null when using !== but not when using the weaker != because JavaScript does some implicit casting in this case.
The main difference between null and undefined is that undefined can also mean something which has not been assigned to.
undefined false
(SomeObject.foo) false false
(SomeObject.foo != null) false true
(SomeObject.foo !== null) true true
(SomeObject.foo != false) true false
(SomeObject.foo !== false) true false
This is taken from this weblog
The problem is that you claim to see the difference, but you don't. Take your example. It should really be:
var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
for (var i = 1; i < List.length; i+=2) {
if (id === List[i].getId()) {
return List[i];
}
}
// returns undefined by default
}
Your algorithm is flawed because you check even indexes (even though you know there's nothing there), and you also misuse null as a return value.
These kind of functions should really return undefined because it means: there's no such data
And there you are in the heart of the problem. If you don't fully understand null and undefined and may use them wrongly sometimes, how can you be so sure that others will use it correctly? You can't.
Then there are Host objects with their nasty behavior, if you ask me, you better off checking for both. It doesn't hurt, in fact, it saves you some headaches dealing with third party code, or the aformentioned non-native objects.
Except for these two cases, in your own code, you can do what #bobince said:
Keep undefined as a special value for signalling when other languages might throw an exception instead.
When to set/use them...
Note that a method without a return statement returns undefined, you shouldn't force this as an expected response, if you use it in a method that should always return a value, then it should represent an error state internally.
Use null for an intentional or non-match response.
As for how/when to check...
undefined, null, 0, an empty string, NaN and false will be FALSE via coercion. These are known as "falsy" values... everything else is true.
Your best bet is coercion then testing for valid exception values...
var something; //undefined
something = !!something; //something coerced into a boolean
//true if false, null, NaN or undefined
function isFalsish(value) {
return (!value && value !== "" && value !== 0);
}
//get number or default
function getNumber(val, defaultVal) {
defaultVal = isFalsish(defaultVal) ? 0 : defaultVal;
return (isFalsish(val) || isNaN(val)) ? defaultVal : +val;
}
Numeric testing is the real bugger, since true, false and null can be coerced into a number, and 0 coerces to false.
I would treat them as 2 completely different values, and check for the one you know might occur.
If you're checking to see if something has been given a value yet, check against undefined.
If you're checking to see if the value is 'nothing,' check against 'null'
A slightly contrived example:
Say you have a series of ajax requests, and you're morally opposed to using callbacks so you have a timeout running that checks for their completion.
Your check would look something like this:
if (result !== undefined){
//The ajax requests have completed
doOnCompleteStuff();
if (result !== null){
//There is actually data to process
doSomething(result);
}
}
tldr; They are two different values, undefined means no value has been given, null means a value has been given, but the value is 'nothing'.

Categories