"To Be or Not to Be" about variables in JavaScript
Just doing a little introduction to JavaScript. I'm used to more than often testing the existence of my pointers in C++ so as not to crash.
Never did I read Hamlet, but I read this page about null
and undefined
in JavaScript.
And in a Nutshell I can:
if (varname == null)
if (varname === null)
if (typeof(varname) != 'undefined')
if (varname != undefined)
if ('varname' in object)
if (object.hasOwnProperty('varname'))
Honestly that is a little too much for me :). What is the classical way in JavaScript for testin开发者_JS百科g variables so as to avoid crashes?
Because of errors thrown reading undeclared globals, checking a variable is best done using the third example, the typeof
example.
if (varname == null)
will tell you whether the value is defined and nullish and throw an error if undeclared.
if (varname === null)
will tell you if the value is defined and exactly null and throw an error if undeclared.
if (typeof(varname) != 'undefined')
will tell you if the variable is defined or not without throwing an error.
if (varname != undefined)
is the opposite of the first.
if ('varname' in object)
will tell you if the object has a property either in itself or somewhere along its prototype chain. This is not guaranteed to work for host objects.
if (object.hasOwnProperty('varname'))
will tell you if the object has an own property, ignoring the prototype chain. This will break if a property named 'hasOwnProperty' has been set.
if (Object.hasOwnProperty.call(object, 'varname'))
is a more reliable version of the last.
the usual way is to use the truthyness of values.
if(varname){
}
This covers most of the examples you gave
The original question was this: What is the classical way in JavaScript for testing variables so as to avoid crashes?
This may be the classical way, and it's certainly a very practical way:
First, you should never, ever have undeclared variables. Use JSLint to be sure that you don't.
If you believe a
is numeric, if (a != null)
will tell you if there's some value in it (though possibly NaN), and if (a)
will tell you if there's some nonzero value in it.
If you believe a
is a string, if (a != null)
will tell you if there's some value in it (though possible the empty string), and if (a)
will tell you if there's at least one character in the string.
If you believe a
is an object, if (a)
will tell you if it's defined. Corollary: if (a && a.prop==7)
is a safe way to check the value of a property.
If you have no idea what a
is supposed to be, then you can still safely test it with if (a)
, though I can't say for sure how useful the results will be.
(Then again, if you have no idea what a
is supposed to be, you have a much bigger problem than can be addressed here.)
It depends on what you have to do with the variable. null
may or may not be a perfectly acceptable value, depending on the context (but I have to admit I have never fonud a good use for null
in javascript). Probably the safest thing is to rely on exceptions to catch problems when something go wrong, instead of trying to anticipate errors by checking for existence of variables.
On the other hand, if you compare something to null
or undefined
it is a good idea to use the ===
operator, which does not need type coercion.
The simpler check if(variable)
will check that variable
is not falsy (that is, it is not null
, undefined
, false
, 0
, NaN
, -0
or the empty string).
Finally the method hasOwnProperty
is often useful when you want to loop over the properties of an object and exclude properties that are inherited from the prototype.
EDIT Pay attention that the above refers to undefined variables, that is, variables which are declared like
var variable;
but are not assigned any value, or missing parameters in functions. One may also want to consider the case of dealing with variables which are undeclared at all. In this case all tests like
if(variable);
if(variable === null);
and so on will fail, reporting an error. The only safe way I know to deal with this case is to check the type of the variable. That is, the typeof
operator can gently handle variables which do not exist.
if(typeof variable === 'undefined')
will be true if either
variable
was declared but is undefined, orvariable
was not declared at all.
In no case this last check will trigger an error.
The first thing you need to understand is strict equality vs truthiness or falsiness. Strict uses three equality signs, where as truthiness uses 2.
These are all equivalent:
var a = false;
if(!a)
if(a == false)
if(a != true)
if(a == 0)
if(a == "")
Using three signs is strict. False means false, not "falsey":
var a = false;
if(a === false)
if(a !== true)
if(a !== anything_else)
id(a === 0) // this will be false
Next, there is a slight difference between null and undefined. Null means declared but nullified (literally set to "null"), undefined means declared but not set:
window.a;
console.log(a); // undefined
window.a = null;
console.log(a); // null
Finally, you wouldn't use typeof for true or false. That's more for string or object type stuff. And variables within objects are properties, not variables, and treated slightly different.
精彩评论