user1679941
user1679941

Reputation:

How can I check if a localstorage variable is null or undefined?

I have this code:

var sideBar = localStorage.getItem('Sidebar');

I want to check if sideBar is defined and not null in an if statement. I am a bit confused I know there's a: sideBar == undefined and sideBar != null

but is there a good way for me to do this test for both of these inside an if:

if (??) 

Upvotes: 27

Views: 61409

Answers (8)

xgqfrms
xgqfrms

Reputation: 12176

just need to use the simple way of ES2020 nullish coalescing operator

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

solution


const sideBar = localStorage.getItem('Sidebar') ?? false;

if(sideBar) {
  // true
} else {
  // false
}

By the way, you don't need to check undefined when you use the localStorage.getItem method.

The getItem() method of the Storage interface, when passed a key name, will return that key's value, or null if the key does not exist, in the given Storage object.

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem

Upvotes: 2

MikhailRatner
MikhailRatner

Reputation: 592

In 2023 the accepted answer should be changed to this:

if (!!token && token.trim() !== 'undefined') {...}

This checks for the value of the token being null, undefined, "" (an empty string) and also for the case that the value of the key is 'undefined' (undefined as a string).

Upvotes: 0

Iman Sedighi
Iman Sedighi

Reputation: 8162

As W3 Manual explicitly explained: The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.

It means, no need to check undefined, If it is undefined then the result of the getItem() method will be null. You need to just check against null.

if (localStorage.getItem("Sidebar") !== null) {
//...
}

Upvotes: 9

Dane Balia
Dane Balia

Reputation: 5367

This should work, and no there isn't a way outside of an "if", even if it ternary operator,

if( !value ) {
}

This will check if there value is "truethy" and should cover both "null" and "undefined".

Upvotes: 1

Juve
Juve

Reputation: 10824

  1. localStorage uses Strings to save the data, i.e., you always have to consider JavaScript String logic when reasoning on null vs. undefined, etc.
  2. If you set the "sideBar" make sure that you do not use "falsy" values. For Strings thats only the empty String "". If you do something else (e.g., some mathematics) before if-checking the variable, you need to consider additional cases.

Here are some tests that show how JavaScript treats certain values in if statements:

> ("")? true : false
false                 # empty string         -> if fails
> (0)? true : false
false                 # Number 0             -> if fails
> ("0")? true : false
true                  # String "0"           -> if succeeds
> (null)? true : false
false                 # JavaScript null      -> if fails
> ("someText")? true : false
true                  # any other String     -> if succeeds
> (" ")? true : false
true                  # a space character    -> if succeeds

I would not use the awkward double checks for null and undefined. If you directly check the result of localStorage.getItem the result is either null or a String. If you then also consider the empty String "" as "falsy", a simple if statement is fine:

var sideBar = localStorage.getItem('Sidebar');

if(sideBar) {
   // do something with the sideBar
}
else {
   // do something without the sideBar
}

To do a real check for the sideBar never being set in localStorage you need to add a check for the empty String and treat that as "defined":

if(sideBar || sideBar === "") {
    // sideBar defined, maybe even as empty String
}
else {
    // sideBar not set in localStorage
}

Upvotes: 8

kinakuta
kinakuta

Reputation: 9037

best practice for checking if a variable is defined and not null:

if (typeof sideBar !== 'undefined' && sideBar !== null)

edited realized you're not checking if something is undefined, you're checking that it's defined, so edited again to answer your request more accurately

Upvotes: 28

evanmcdonnal
evanmcdonnal

Reputation: 48096

Yes, you bind the two conjunctively (meaning both must be true) with &&

So... if (sideBar === undefined && sideBar !== null) will evaluate to true if and only if each condition evaluates to true.

Upvotes: 1

y_s
y_s

Reputation: 138

If statements can be joined using &&

It is advisable to use '==='. e.g. if (sideBar === undefined && sideBar !== null)

http://www.w3schools.com/jsref/jsref_undefined.asp

Upvotes: 0

Related Questions