typeof !== undefined vs. != null
typeof
is safer as it allows the identifier to never have been declared before:
if(typeof neverDeclared === "undefined") // no errors
if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined
What is the difference between null and undefined in JavaScript?
undefined
means a variable has been declared but has not yet been assigned a value :
var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined
typeof a == 'undefined' vs typeof a === 'undefined'
In this instance, since typeof
will always give you a string: It isn't better (nor is it worse). It makes no practical difference.
In general, using ===
is preferred because it forces you to be explicit about your types and saves you from getting results you don't expect when JavaScript's type resolution rules are unintuitive.
Is there any benefit of checking typeof a === undefined instead of a === undefined?
According to a related question undefined
is not assured to be the thing you expect it to be:
var undefined = 'uh oh'
if (numLines === undefined) {
// Seems safe but isn't
}
else if (typeof(numlines) == 'undefined') {
// Actually gets it.
}
It's very odd that undefined
is not nailed down in JavaScript, but that's how it is with the ECMA standard.
variable === undefined vs. typeof variable === undefined
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.
How to check for an undefined or null variable in JavaScript?
You have to differentiate between cases:
- Variables can be
undefined
or undeclared. You'll get an error if you access an undeclared variable in any context other thantypeof
.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error
A variable that has been declared but not initialized is undefined
.
let foo;
if (foo) //evaluates to false because foo === undefined
Undefined properties , like
someExistingObj.someUndefProperty
. An undefined property doesn't yield an error and simply returnsundefined
, which, when converted to a boolean, evaluates tofalse
. So, if you don't care about0
andfalse
, usingif(obj.undefProp)
is ok. There's a common idiom based on this fact:value = obj.prop || defaultValue
which means "if
obj
has the propertyprop
, assign it tovalue
, otherwise assign the default valuedefautValue
".Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the
in
operator insteadvalue = ('prop' in obj) ? obj.prop : defaultValue
typeof error comparing to undefined - data is null
In javascript, the opening brace placement matters. Your code might not mean what you think it means due to your placement of the opening brace.
Also, the use of .success and .error have been deprecated. Consider using .done or .fail methods.
Typeof null returns an object, so if data.errors is null, your check will fail. Consider doing
if (!data.errors) {
...
}
Lastly, the data being returned from the server might be null. This would cause the null exception that you are seeing. You can debug your application to see if this is the case.
How can I determine if a variable is 'undefined' or 'null'?
You can use the qualities of the abstract equality operator to do this:
if (variable == null){
// your code here.
}
Because null == undefined
is true, the above code will catch both null
and undefined
.
Why is null an object and what's the difference between null and undefined?
(name is undefined)
You: What is name
? (*)
JavaScript: name
? What's a name
? I don't know what you're talking about. You haven't ever mentioned any name
before. Are you seeing some other scripting language on the (client-)side?
name = null;
You: What is name
?
JavaScript: I don't know.
In short; undefined
is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null
is where the thing is known to exist, but it's not known what the value is.
One thing to remember is that null
is not, conceptually, the same as false
or ""
or such, even if they equate after type casting, i.e.
name = false;
You: What is name
?
JavaScript: Boolean false.
name = '';
You: What is name
?
JavaScript: Empty string
*: name
in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.
Related Topics
Chrome Extension - How to Get Http Response Body
Should I Use Encodeuri or Encodeuricomponent for Encoding Urls
How to Wait for a JavaScript Promise to Resolve Before Resuming Function
Does JavaScript Support 64-Bit Integers
How to Save JSON to Local Text File
".Addeventlistener Is Not a Function" Why Does This Error Occur
How to Rotate a Single Object on an HTML 5 Canvas
Change the Style of an Entire CSS Class Using JavaScript
Javascript: Get Image Dimensions
What Is "Context" in Jquery Selector
How to Include Js File in Another Js File
How to Concatenate Properties from Multiple JavaScript Objects
What the Difference of This.State and This.Setstate in Reactjs
Password Encryption at Client Side
Change Form Values After Submit Button Pressed