Comparison to null does not actually prevent errors. Comparing a variable against null typically does not provide enough information about the value to determine whether it's safe to proceed. Fortunately, JavaScript has a number of ways to determine the true calue of a variable.
There are 5 primitive types in JavaScript:
- string
- number
- boolean
- Null
- Undefined
The typeof operator is the best option to determine a value a primitive value. It returns a string indicating the type of value. It is not a function.
typeof <variable-name>Using typeof for detecting four primitive value types is the safest way to code defensively.
// detect a string
if (typeof name === 'string') {
anotherName = name.substring(3);
}
// detect a number
if (typeof count === 'number') {
updateCount(count);
}
// detect a boolean
if (typeof found === 'boolean'&& found) {
message('Found!');
}
// detect undefined
if (typeof MyApp === 'undefined') {
MyApp = {
// code
}
}typeof operator is also unique in that it can be used on an undeclared variable without throwing an error. Both undeclared variables and variables whoes value is undefined return "undefined" when typeof is used.
The last primitive value, null, is the one you normally should not check for because typeof does not give enought information about whether the value was expected. There is one exception: if on of the expected values is actually null, then it is OK to test for it directly. But the comparison should be done using === pr !== against null.
// if you must test for null, this is the way to go
var element = document.getElementById ('my-div');
if (element !== null) {
element.className = 'found';
}It is possible for document.getElementById () to return null if the given DOM element is not found. The method will return null or an element. Because null is one of the expected outcomes, it is OK to test for it using !==.
Also known as objects. In JavaScript any value that is not a primitive is a reference. There are several built-in reference types such as Object Array, Date and Error, just to name a few. typeof returns "object for any type of object as well and null and is not useful.
The instanceof is best for detecting values of a reference type.
// detect a Date
if (value instanceof Date) {
console.log(value.getFullYear());
}
// detect a RegExp
if (value.test instanceof RegExp) {
console.log('matches');
}
// detect an Error
if (value instanceof Error) {
throw value;
}Functions are technically reference types in JavaScript. Using typeof is the best way to detect functions.
function myFunc() {}
// Good
console.log(typeof myFunc === 'function'); // true Douglas Crockford duck typing relies on the fact that arrays are the only objects with a sort() method but this approach yeild true for any other type of object with a sort() method too.
// Duck Typing Arrays
function isArray(value) {
return typeof value.sort === 'function';
}To determine whether a property is present in an object.
The best way to detect the presense of a property is to use the in operator which checks for the prescense of the named property without reading its value.
var object = {
count: 0,
related: null
};
// Good
if ('count' in object {
// this executes
}
if ('related' in object {
// this executes
}To check for property existence on the object instace use hasOwnProperty() method.
// Good for all non-DOM objects
if (object.hasOwnProperty('related')) {
// this executes
}
// Good when your are not sure
if (hasOwnProperty in object && object.hasOwnProperty('related')) {
// this executes
}