845

How can I check for null values in JavaScript? I wrote the code below but it didn't work.

if (pass == null || cpass == null || email == null || cemail == null || user == null) {      

    alert("fill all columns");
    return false;  

}   

And how can I find errors in my JavaScript programs?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Mahdi_Nine
  • 14,205
  • 26
  • 82
  • 117
  • 1
    Are you sure the values you are testing are actually null and not just empty string? – Jan-Peter Vos May 14 '11 at 18:18
  • 109
    testing `null` in js should be done with the strict operator `===` – davin May 14 '11 at 18:19
  • @Hogan, I meant strict, and I assume by the upvotes that the readers interpreted it that way... – davin May 14 '11 at 18:22
  • 3
    @davin - true, but not the problem here since if it were the statement would still work. –  May 14 '11 at 18:22
  • 3
    @cwolves, if I thought it were the problem I would have made that comment an answer. Check out my wording, I'm clearly making a general statement about the language in reference to the OP's practise, and not proposing that this solves his problem. – davin May 14 '11 at 18:24
  • @ic3b3rg I *think* I agree with your rollbacks, but I'd be happier if you explained them. – TRiG Jul 18 '14 at 10:55
  • 3
    @TRiG the proposed changes fundamentally alter the nature of the question to the point where the answers (not just mine) lose context and don't make sense. The edit should just be a comment. – ic3b3rg Jul 22 '14 at 04:50

24 Answers24

1047

JavaScript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:

if(!pass || !cpass || !email || !cemail || !user){

Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN.

Please note that if you are specifically checking for numbers, it is a common mistake to miss 0 with this method, and num !== 0 is preferred (or num !== -1 or ~num (hacky code that also checks against -1)) for functions that return -1, e.g. indexOf).

Ryan M
  • 18,333
  • 31
  • 67
  • 74
  • 7
    It would be very useful to know which parts of this test for which values. Sometimes you're looking for one in particular. – inorganik Apr 19 '13 at 19:28
  • 2
    Somewhat of a late statement, but yes, you can perform test against each one @inorganik , see my answer below – WebWanderer Dec 18 '14 at 16:02
  • 88
    Readers, please be careful when using this type of test on numeric data. Do not use `!` or `!!` to test for `null` or `undefined` on typically-numeric data unless you also want to throw away values of 0. – NickS Feb 24 '16 at 21:06
  • 2
    Have to agree with NickS. If you're specifically testing for null, it's possible to get false positives with this type of boolean NOT test. This is an overbroad solution to a specific question. – LetMyPeopleCode Jun 24 '16 at 19:35
  • 7
    The answer itself states this: "...and the numbers `0`...". I believe this answer is perfectly appropriate for the question as given the context (which I'm inferring is "username, password, email"), they're not checking for `0` values. Given the popularity of this question and answer, however, I agree that it's worth mentioning in the answer itself. –  Jun 24 '16 at 20:13
  • 3
    @zyklus Even if he is asking about usernames and passwords, it's possible that functions could be gathering the data from the forms and returning null if an empty string is found. But much more importantly, Stack Overflow questions come up as google results all the time, so many people who are curious how to check for a null value will be directed here and will see your answer first. It probably would have been best to answer the question that was asked and then address the specifics of this code. Sorry if that upsets you, SO asks me to comment when I downvote an answer so I am doing that. – Hendeca Jul 04 '16 at 01:44
  • 1
    @Hendeca - The context of answering a question for the 420,000 people that have seen this question is _very_ different than the context of answering it for the OP. I'll consider re-wording the answer. –  Jul 04 '16 at 02:08
693

To check for null SPECIFICALLY you would use this:

if (variable === null)

This test will ONLY pass for null and will not pass for "", undefined, false, 0, or NaN.

Additionally, I've provided absolute checks for each "false-like" value (one that would return true for !variable).

Note, for some of the absolute checks, you will need to implement use of the absolutely equals: === and typeof.

I've created a JSFiddle here to show all of the individual tests working

Here is the output of each check:

Null Test:

if (variable === null)

- variable = ""; (false) typeof variable = string

- variable = null; (true) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Empty String Test:

if (variable === '')

- variable = ''; (true) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number




Undefined Test:

if (typeof variable == "undefined")

-- or --

if (variable === undefined)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (true) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



False Test:

if (variable === false)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (true) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Zero Test:

if (variable === 0)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (true) typeof variable = number

- variable = NaN; (false) typeof variable = number



NaN Test:

if (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)

-- or --

if (isNaN(variable))

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (true) typeof variable = number

As you can see, it's a little more difficult to test against NaN;

isherwood
  • 58,414
  • 16
  • 114
  • 157
WebWanderer
  • 10,380
  • 3
  • 32
  • 51
  • 9
    What is the purpose of type checking if you use `===` strict equality? Thanks. Also for NaN test you can use `isNaN(value)` that will return `true` only if variable equals NaN. – Michael Malinovskij Feb 11 '15 at 13:20
  • 17
    Is there a case where `variable === null` but is not of type "object"? If there is not, why not simplify the check to `variable === null`, throwing out the second conjunct? Thanks. – Hunan Rostomyan Apr 04 '15 at 22:19
  • 7
    @HunanRostomyan Good question, and honestly, no, I do not think that there is. You are most likely safe enough using `variable === null` which I just tested [here in this JSFiddle](https://jsfiddle.net/WebWanderer/8n9vtyek/6/). The reason I also used ` && typeof variable === 'object'` was not only to illustrate the interesting fact that a `null` value is a typeof `object`, but also to keep with the flow of the other checks. But yes, in conclusion, you are safe to use simply `variable === null`. – WebWanderer Apr 06 '15 at 14:59
  • 1
    https://jsfiddle.net/neoaptt/avt1cgem/1/ Here is this answer broken out into functions. Not very usefull, but I did it anyways. – Roger Apr 18 '16 at 18:22
  • 1
    I'm going to do something that is almost never a good idea: change the code in this answer. Specifically, remove the totally unnecessary test for type object, when checking for null. This is a ***fundamental*** code snippet: not a good idea to have *even a single beginner* mis-learn that they need to do that verbose test. – ToolmakerSteve Nov 01 '19 at 11:54
  • 1
    @ToolmakerSteve Yea, I think it's time to remove that, and to possibly clean this up. It is not necessary as part of the test, but was provided to note that `null` is `typeof Object`. It should be a comment instead. +1 – WebWanderer Nov 04 '19 at 21:17
  • Readers: Disregard my previous statements about `isNaN`. This is a perfectly fine way to test for the existence of `NaN` in JavaScript. – WebWanderer Nov 25 '19 at 19:23
  • Let me share a very interesting review I found about how `null` was erroneously typed as `object`: https://alexanderell.is/posts/typeof-null/ – Kar.ma Nov 05 '20 at 11:11
75

just replace the == with === in all places.

== is a loose or abstract equality comparison

=== is a strict equality comparison

See the MDN article on Equality comparisons and sameness for more detail.

ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
  • 7
    This only works if you consider `undefined` to be not `null`. Otherwise it will lead to a lot of unexpected behavior. Generally if you're interested in both `null`/`undefined` but not falsy values, then use `==` (one of the few cases when you should do so). – Andrew Mao May 11 '16 at 22:40
  • 2
    @AndrewMao `undefined` **is not** `null`: http://stackoverflow.com/a/5076962/753237 – ic3b3rg Jun 27 '16 at 02:18
  • 4
    I believe that's what @AndrewMao was saying, really. His first sentence might be rewritten "This only works in situations where undefined and null are not practical equivalents." – BobRodes Jun 30 '16 at 02:22
  • 2
    @BobRodes Thanks for clarifying my poor writing, I appreciate it :) – Andrew Mao Jun 30 '16 at 15:16
  • @AndrewMao You are very welcome. And I wouldn't call your writing poor, personally; I'd say it's a good deal better than average. :) – BobRodes Jun 30 '16 at 18:23
54

You can check if some value is null as follows

[pass,cpass,email,cemail,user].some(x=> x===null) 

let pass=1;
let cpass=2;
let email=3;
let cemail=null;
let user=5;

if ( [pass,cpass,email,cemail,user].some(x=> x===null) ) {     
    alert("fill all columns");
    //return false;  
}   

BONUS: Why === is more clear than == (source)

a == b

Enter image description here

a === b

Enter image description here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 5
    great 2 diagrams, I took the liberty of merging them both: https://docs.google.com/drawings/d/1o4_lJbSaDNNuVBXyVXds3UIEkjz9Znnwqwc38VLDifI/edit?usp=sharing – abernier Nov 27 '20 at 09:15
  • In addition to the 2 diagrams above. While `if ([] == false)` is true (as shown in your diagram), `if ([])` also evaluates to true. – bvdb Mar 03 '21 at 22:51
  • 3
    In fact, they now have a merged table at https://dorey.github.io/JavaScript-Equality-Table/unified/ – Infigon Aug 22 '22 at 23:09
47

Strict equality operator:-

We can check null by ===

if ( value === null ){

}

Just by using if

if( value ) {

}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • false
  • 0
Arshid KV
  • 9,631
  • 3
  • 35
  • 36
19

At first sight, it looks like a simple trade-off between coverage and strictness.

  • == covers multiple values, can handle more scenarios in less code.
  • === is the most strict, and that makes it predictable.

Predictability always wins, and that appears to make === a one-fits-all solution.

enter image description here

But it is wrong. Even though === is predictable, it does not always result in predictable code, because it overlooks scenarios.

const options = { };
if (options.callback !== null) {
  options.callback();      // error --> callback is undefined.
}

In general == does a more predictable job for null checks:

  • In general, null and undefined both mean the same thing: "something's missing". For predictability, you need to check both values. And then == null does a perfect job, because it covers exactly those 2 values. (i.e. == null is equivalent to === null && === undefined)

  • In exceptional cases you do want a clear distinction between null and undefined. And in those cases you're better of with a strict === undefined or === null. (e.g. a distinction between missing/ignore/skip and empty/clear/remove.) But it is rare.

It is not only rare, it's something to avoid. You can't store undefined in a traditional database. And you shouldn't rely on undefined values in your API designs neither, due to interopability reasons. But even when you don't make a distinction at all, you can't assume that undefined won't happen. People all around us indirectly take actions that generalize null/undefined (which is why questions like this are closed as "opinionated".).

So, to get back to your question. There's nothing wrong with using == null. It does exactly what it should do.

// FIX 1 --> yes === is very explicit
const options = { };
if (options.callback !== null && 
    options.callback !== undefined) {
  options.callback();
}


// FIX 2 --> but == covers both
const options = { };
if (options.callback != null) {
  options.callback();
}

// FIX 3 --> optional chaining also covers both.
const options = { };
options.callback?.();
bvdb
  • 22,839
  • 10
  • 110
  • 123
12

Improvement over the accepted answer by explicitly checking for null but with a simplified syntax:

if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
    // your code here ...
}

// Test
let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test

if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
    // your code here ...
    console.log ("Yayy! None of them are null");
} else {
    console.log ("Oops! At-lease one of them is null");
}
Deekshith
  • 1,544
  • 2
  • 14
  • 15
9

Firstly, you have a return statement without a function body. Chances are that that will throw an error.

A cleaner way to do your check would be to simply use the ! operator:

if (!pass || !cpass || !email || !cemail || !user) {

    alert("fill all columns");

}
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
Joey C.
  • 2,168
  • 2
  • 16
  • 14
5

to check for undefined and null in javascript you need just to write the following :

if (!var) {
        console.log("var IS null or undefined");
} else {
        console.log("var is NOT null or undefined");
}
Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
Nejmeddine Jammeli
  • 1,011
  • 9
  • 17
5

In JavaScript, no string is equal to null.

Maybe you expected pass == null to be true when pass is an empty string because you're aware that the loose equality operator == performs certain kinds of type coercion.

For example, this expression is true:

'' == 0

In contrast, the strict equality operator === says that this is false:

'' === 0

Given that '' and 0 are loosely equal, you might reasonably conjecture that '' and null are loosely equal. However, they are not.

This expression is false:

'' == null

The result of comparing any string to null is false. Therefore, pass == null and all your other tests are always false, and the user never gets the alert.

To fix your code, compare each value to the empty string:

pass === ''

If you're certain that pass is a string, pass == '' will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.

If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.

Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47
5

Actually I think you may need to use if (value !== null && value !== undefined) because if you use if (value) you may also filter 0 or false values.

Consider these two functions:

const firstTest = value => {
    if (value) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}
const secondTest = value => {
    if (value !== null && value !== undefined) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}

firstTest(0);            // result: failed
secondTest(0);           // result: passed

firstTest(false);        // result: failed
secondTest(false);       // result: passed

firstTest('');           // result: failed
secondTest('');          // result: passed

firstTest(null);         // result: failed
secondTest(null);        // result: failed

firstTest(undefined);    // result: failed
secondTest(undefined);   // result: failed

In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0 or false or '' values. so I used the second test, but you may need to filter them too which may cause you to use first test.

Naeem Baghi
  • 811
  • 2
  • 14
  • 29
  • 1
    `value !== null || value !== undefined` is always true. I think you meant `value !== null && value !== undefined`. That's actually the same as `value != null` (which checks exactly for null and undefined.) – bvdb Mar 03 '21 at 22:42
  • @bvdb Sorry, in the code I used the correct expression, but up there I forgot :-D I fixed it, thank you. – Naeem Baghi Apr 04 '21 at 05:47
5

you can use try catch finally

 try {
     document.getElementById("mydiv").innerHTML = 'Success' //assuming "mydiv" is undefined
 } catch (e) {

     if (e.name.toString() == "TypeError") //evals to true in this case
     //do something

 } finally {}   

you can also throw your own errors. See this.

Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
DrStrangeLove
  • 11,227
  • 16
  • 59
  • 72
  • 1
    i think this qualifies as 'paranoid' code. if you really wrote something like this, it would be with an understanding that "mydiv" couldn't possibly not exist. we shouldn't reach this code unless we're confident that's the case, and we'd have plenty of avenues such as response codes to make sure we're confident before attempting such a line. – calql8edkos May 05 '15 at 16:09
  • Do not use try and catch for flow of control. This is not a good solution. – Andrew S May 22 '20 at 19:53
4

This is a comment on WebWanderer's solution regarding checking for NaN (I don't have enough rep yet to leave a formal comment). The solution reads as

if(!parseInt(variable) && variable != 0 && typeof variable === "number")

but this will fail for rational numbers which would round to 0, such as variable = 0.1. A better test would be:

if(isNaN(variable) && typeof variable === "number")
Gabriel
  • 580
  • 4
  • 14
  • 1
    Thanks for pointing out the bug Gabriel, I've put the fix into my answer. Aside from that, I was able to fix the test by changing `parseInt` to `parseFloat` (which should have been obvious to me in the first place). I avoided using the `isNan` function because I feel as if many developers view functions such as `isNaN` as some sort of "magic box" that values go into and booleans come out of, and I wanted to should the test a little more in depth. But yes, your suggested test will work and is perfectly fine to use. Sorry I didn't notice your post until now. – WebWanderer Apr 16 '15 at 15:06
  • 1
    Great, that seems to work. Thanks for the comment on why you avoided `isNaN` as well, I can get behind that logic. There's also the Underscore.js method, which seems even more confusing/blackbox, but worth noting anyway because it takes advantage of `NaN !== NaN`. `Object.prototype.toString.call(variable) === '[object Number]' && variable !== +variable` – Gabriel Apr 18 '15 at 00:23
4

You can use lodash module to check value is null or undefined

_.isNil(value)
Example 

 country= "Abc"
    _.isNil(country)
    //false

   state= null
    _.isNil(state)
    //true

city= undefined
    _.isNil(state)
    //true

   pin= true
    _.isNil(pin)
    // false   

Reference link: https://lodash.com/docs/#isNil

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ashita.gupta
  • 321
  • 3
  • 5
4

The 'Object.is()' method can be used to determine if two values are the same value. So, you can use it to check whether the object is null or not.

Check for null values

let testA = null; //null
//console.log(Object.is(testA, null)); //true //null === null

if(Object.is(testA, null)) {
  console.log("This is a Null Value");
}
Output:
This is a Null Value
let x = null;
if (x === null) {
  console.log("x is null");
}
Output:
x is null

Check for undefined values (A variable has been declared, but a value has not been assigned.)

let testB; //undefined
//console.log(Object.is(testB, undefined)); //true //undefined === undefined

if(Object.is(testB, undefined)) {
  console.log("This is an undefined Value");
}
Output:
This is an undefined Value

If the object has not been declared, this cannot be used. As an alternative, you may try this:

if (typeof x === "undefined") {
  console.log("x is undefined");
}
Output:
The value is either undefined or null

Mozilla Object.is(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is

DxTx
  • 3,049
  • 3
  • 23
  • 34
  • 1
    Note by "undefined" here you mean that the variable is created/initialized but a value is just not assigned to it. "Undefined" typically means that the variable doesn't exist at all, and in that case your code wouldn't be applicable. – Uriahs Victor Feb 11 '23 at 23:22
  • @UriahsVictor, thanks, I updated the answer a little bit. – DxTx Feb 12 '23 at 03:26
3

AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is undefined. so we can check variable even if it would be an object holding some instance in place of value.

create a helper method for checking nullity that returns true and use it in your API.

helper function to check if variable is empty:

function isEmpty(item){
    if(item){
        return false;
    }else{
        return true;
    }
}

try-catch exceptional API call:

try {

    var pass, cpass, email, cemail, user; // only declared but contains nothing.

    // parametrs checking
    if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
        console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
    }else{
        // do stuff
    }

} catch (e) {
    if (e instanceof ReferenceError) {
        console.log(e.message); // debugging purpose
        return true;
    } else {
        console.log(e.message); // debugging purpose
        return true;
    }
}

some test cases:

var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true

console.log("isEmpty? "+isEmpty(item));
ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196
Kaleem Ullah
  • 6,799
  • 3
  • 42
  • 47
  • 1
    What? This answer has nothing to do with this post. Did you post this answer on this thread by accident? – WebWanderer Nov 02 '15 at 20:32
  • This `isEmpty` function behaves exactly like `!`. No need to invent a function. Just do `if (!pass || !cpass || !email ...)`. (Which is already shown in the accepted answer.) And per WebWanderer's comment, the middle part of this post, "try-catch exceptional API call", does not appear to be relevant to this question. Please explain your intent - when is that useful? How does that relate to the question? – ToolmakerSteve Nov 01 '19 at 12:57
2

I found a another way to test if the value is null:

if(variable >= 0 && typeof variable === "object")

null acts as a number and object at the same time. Comparing null >= 0 or null <= 0 results in true. Comparing null === 0 or null > 0 or null < 0 will result in false. But as null is also an object we can detect it as a null.

I made a more complex function natureof witch will do better than typeof and can be told what types to include or keep grouped

/* function natureof(variable, [included types])
included types are 
    null - null will result in "undefined" or if included, will result in "null"
    NaN - NaN will result in "undefined" or if included, will result in "NaN"
    -infinity - will separate negative -Inifity from "Infinity"
    number - will split number into "int" or "double"
    array - will separate "array" from "object"
    empty - empty "string" will result in "empty" or
    empty=undefined - empty "string" will result in "undefined"
*/
function natureof(v, ...types){
/*null*/            if(v === null) return types.includes('null') ? "null" : "undefined";
/*NaN*/             if(typeof v == "number") return (isNaN(v)) ? types.includes('NaN') ? "NaN" : "undefined" : 
/*-infinity*/       (v+1 === v) ? (types.includes('-infinity') && v === Number.NEGATIVE_INFINITY) ? "-infinity" : "infinity" : 
/*number*/          (types.includes('number')) ? (Number.isInteger(v)) ? "int" : "double" : "number";
/*array*/           if(typeof v == "object") return (types.includes('array') && Array.isArray(v)) ? "array" : "object";
/*empty*/           if(typeof v == "string") return (v == "") ? types.includes('empty') ? "empty" : 
/*empty=undefined*/ types.includes('empty=undefined') ? "undefined" : "string" : "string";
                    else return typeof v
}

// DEMO
let types = [null, "", "string", undefined, NaN, Infinity, -Infinity, false, "false", true, "true", 0, 1, -1, 0.1, "test", {var:1}, [1,2], {0: 1, 1: 2, length: 2}]

for(i in types){
console.log("natureof ", types[i], " = ", natureof(types[i], "null", "NaN", "-infinity", "number", "array", "empty=undefined")) 
}
Tarmo Saluste
  • 585
  • 6
  • 18
2

I made this very simple function that works wonders:

function safeOrZero(route) {
  try {
    Function(`return (${route})`)();
  } catch (error) {
    return 0;
  }
  return Function(`return (${route})`)();
}

The route is whatever chain of values that can blow up. I use it for jQuery/cheerio and objects and such.

Examples 1: a simple object such as this const testObj = {items: [{ val: 'haya' }, { val: null }, { val: 'hum!' }];};.

But it could be a very large object that we haven't even made. So I pass it through:

let value1 = testobj.items[2].val;  // "hum!"
let value2 = testobj.items[3].val;  // Uncaught TypeError: Cannot read property 'val' of undefined

let svalue1 = safeOrZero(`testobj.items[2].val`)  // "hum!"
let svalue2 = safeOrZero(`testobj.items[3].val`)  // 0

Of course if you prefer you can use null or 'No value'... Whatever suit your needs.

Usually a DOM query or a jQuery selector may throw an error if it's not found. But using something like:

const bookLink = safeOrZero($('span.guidebook > a')[0].href);
if(bookLink){
  [...]
}
Neithan Max
  • 11,004
  • 5
  • 40
  • 58
2

Simple Solution for empty values:

function isEmpty(value) {
        return (
            value === null || value === undefined || value === '' ||
            (Array.isArray(value) && value.length === 0) ||
            (!(value instanceof Date) && typeof value === 'object' && Object.keys(value).length === 0)
        );
    }
Amr Omar
  • 399
  • 5
  • 12
2

This is a very non-human code. But works:

if((pass, cpass, email, cemail, user !== null)){

Just try it out and help the answer

Mr White
  • 103
  • 1
  • 7
1

What about optional check with operator ?

for example:

// check mother for null or undefined and 
// then if mother exist check her children also
// this 100% sure it support and valid in JS today.
// Apart of that C# have almost the same operator using the same way
if (mother?.children) {

}
else {
 // it is null, undefined, etc...

}
Pit
  • 395
  • 2
  • 11
0

Try this:

if (!variable && typeof variable === "object") {
    // variable is null
}
THX-1138
  • 21,316
  • 26
  • 96
  • 160
user5520516
  • 521
  • 2
  • 1
0

This will not work in case of Boolean values coming from DB for ex:

 value = false

 if(!value) {
   // it will change all false values to not available
   return "not available"
 }
Codiee
  • 3,047
  • 2
  • 17
  • 18
0

Checking error conditions:

// Typical API response data
let data = {
  status: true,
  user: [],
  total: 0,
  activity: {sports: 1}
}

// A flag that checks whether all conditions were met or not
var passed = true;

// Boolean check
if (data['status'] === undefined || data['status'] == false){
  console.log("Undefined / no `status` data");
  passed = false;
}

// Array/dict check
if (data['user'] === undefined || !data['user'].length){
  console.log("Undefined / no `user` data");
  passed = false;
}

// Checking a key in a dictionary
if (data['activity'] === undefined || data['activity']['time'] === undefined){
   console.log("Undefined / no `time` data");
   passed = false;
}

// Other values check
if (data['total'] === undefined || !data['total']){
  console.log("Undefined / no `total` data");
  passed = false;
}

// Passed all tests?
if (passed){
  console.log("Passed all tests");
}
P-S
  • 3,876
  • 1
  • 29
  • 26