What is the difference between null and undefined in JavaScript? - Stack Overflow
lodash - Javascript how to set null/undefined values in an Object to an empty string - Stack Overflow
How can I determine if a variable is 'undefined' or 'null'?
How can I check for "undefined" in JavaScript? - Stack Overflow
Videos
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
null is an assignment value. It can be assigned to a variable as a representation of no value :
var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object
From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Proof :
console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)
and
null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
The difference can be explained with toilet tissue holder:
A non-zero value is like a holder with roll of toilet tissue and there's tissue still on the tube.
A zero value is like a holder with an empty toilet tissue tube.
A null value is like a holder that doesn't even have a tissue tube.
An undefined value is similar to the holder itself being missing.
You can use _.mapValues() to iterate the values and replace them, and _.isNil() to check if a value is null or undefined:
const obj = {
a: '23',
b: 'Red',
c: null,
}
const result = _.mapValues(obj, v => _.isNil(v) ? '' : v)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
You can use a combination of Object.keys() and .forEach():
Object.keys(yourObject).forEach(function(key, index) {
if (this[key] == null) this[key] = "";
}, yourObject);
The == comparison will check for both null and undefined. Passing yourObject as the second parameter to .forEach() will cause this to be bound to it inside the callback function.
edit — originally I wrote this as an => function, but that won't work because we need this to work in the traditional way.
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.
The standard way to catch null and undefined simultaneously is this:
if (variable == null) {
// do something
}
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}
When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null.
Edit again
The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catch if you are working with input you don't have control over.
You should not have any references to undeclared variables in your code.
If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example:
// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"
But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.
"theFu" in window; // true
"theFoo" in window; // false
If you are interested in knowing whether the variable hasn't been declared or has the value undefined, then use the typeof operator, which is guaranteed to return a string:
if (typeof myVar !== 'undefined')
Direct comparisons against undefined are troublesome as undefined can be overwritten.
window.undefined = "foo";
"foo" == undefined // true
As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.
if (window.myVar) will also include these falsy values, so it's not very robust:
false 0 "" NaN null undefined
Thanks to @CMS for pointing out that your third case - if (myVariable) can also throw an error in two cases. The first is when the variable hasn't been defined which throws a ReferenceError.
// abc was never declared.
if (abc) {
// ReferenceError: abc is not defined
}
The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,
// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", {
get: function() { throw new Error("W00t?"); },
set: undefined
});
if (myVariable) {
// Error: W00t?
}
I personally use
myVar === undefined
Warning: Please note that === is used over == and that myVar has been previously declared (not defined).
I do not like typeof myVar === "undefined". I think it is long winded and unnecessary. (I can get the same done in less code.)
Now some people will keel over in pain when they read this, screaming: "Wait! WAAITTT!!! undefined can be redefined!"
Cool. I know this. Then again, most variables in Javascript can be redefined. Should you never use any built-in identifier that can be redefined?
If you follow this rule, good for you: you aren't a hypocrite.
The thing is, in order to do lots of real work in JS, developers need to rely on redefinable identifiers to be what they are. I don't hear people telling me that I shouldn't use setTimeout because someone can
window.setTimeout = function () {
alert("Got you now!");
};
Bottom line, the "it can be redefined" argument to not use a raw === undefined is bogus.
(If you are still scared of undefined being redefined, why are you blindly integrating untested library code into your code base? Or even simpler: a linting tool.)
Also, like the typeof approach, this technique can "detect" undeclared variables:
if (window.someVar === undefined) {
doSomething();
}
But both these techniques leak in their abstraction. I urge you not to use this or even
if (typeof myVar !== "undefined") {
doSomething();
}
Consider:
var iAmUndefined;
To catch whether or not that variable is declared or not, you may need to resort to the in operator. (In many cases, you can simply read the code O_o).
if ("myVar" in window) {
doSomething();
}
But wait! There's more! What if some prototype chain magic is happening…? Now even the superior in operator does not suffice. (Okay, I'm done here about this part except to say that for 99% of the time, === undefined (and ****cough**** typeof) works just fine. If you really care, you can read about this subject on its own.)