user1321237
user1321237

Reputation:

How can I check if two values are not equal to null with javascript?

I have the following code:

var store = window.localStorage;
var a = store.getItem('AccountID');
var b = store.getItem('CityID')

How can I make it so my refreshGrid("Page"); function only runs if both of these are set to values?

Upvotes: 0

Views: 9543

Answers (4)

talha2k
talha2k

Reputation: 25650

You can use this:

var a; var b;

if (a == null && b == null) {
   //a and b are null
}

OR

if (!a && !b) {
   //a and b are null, undefined, 0 or false
}

For James: alert(null == undefined) // returns true

Hope this helps.

Upvotes: 1

David K
David K

Reputation: 690

I think the following code is what your looking for.

if(!!a && !!b){

  alert("this is not null")

}else{

  alert("this is null")

}

Upvotes: 0

Gerardo Lima
Gerardo Lima

Reputation: 6703

Use a guard condition at the top of your function:

function myFunction() {
    if(a==null || b==null) return;
    // ... rest of the code here
}

Upvotes: 0

James Allardice
James Allardice

Reputation: 165951

If you want to check that they are explicity null, just compare the values to null:

if(a !== null && b !== null) {
    //Neither is null
}

If you are storing values in there that should always evaluate to true, you can skip the equality checks (if nothing is stored in that particular storage item this will still fail, since null is falsy):

if(a && b) {
    //Neither is falsy
}

Upvotes: 7

Related Questions