25

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 (??) 
  • Possible duplicate of [How to check for an undefined or null variable in JavaScript?](http://stackoverflow.com/questions/2559318/how-to-check-for-an-undefined-or-null-variable-in-javascript) – Kristján Nov 07 '15 at 17:03

8 Answers8

27

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

kinakuta
  • 9,029
  • 1
  • 39
  • 48
  • 1
    Checking against null is unnecessary. Instead of checking against undefined we could just check it against null. If it is undefined then automatically the result of getItem() will be null. – Iman Sedighi Aug 04 '14 at 10:21
  • You're right in that the code as posted doesn't require the explicit check for undefined. However, the answer is provided as a general purpose answer to checking a variable for null or undefined. Changing code order, for example, could create a situation where a variable was checked before assigning a value, while this check would still work regardless. – kinakuta Aug 04 '14 at 15:50
  • I'm not sure if this is changed, but in my example I have an item that has a value "undefined" and `!== null` returns true. – DjangoDev1 Apr 01 '21 at 00:09
  • In 2023 I would go for this in TypeScript: ```if (!!token && token.trim() !== 'undefined') {...}```. This checks for ```null```, ```undefined```, ```""``` (empty string) and also for the case that the value of the key is ```'undefined'``` (a string). – MikhailRatner Mar 07 '23 at 15:41
9

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) {
//...
}
Iman Sedighi
  • 7,624
  • 4
  • 48
  • 55
  • 1
    I think this one is the best answer, no need to check `undefined` because it does not exist as the return value of localStorage.getItem method; I think this one is the best answer, no need to check `undefined` because it does not exist as the return value of localStorage.getItem method; – xgqfrms Jan 01 '22 at 09:46
8
  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
}
Juve
  • 10,584
  • 14
  • 63
  • 90
  • 1
    you can set a value in localStorage to an empty string which means it's not equivalent to it being undefined or null – kinakuta Nov 15 '12 at 06:40
  • Yes that is what I also discuss in my answer. The empty `String` needs to be treated as "falsy" value. – Juve Nov 15 '12 at 06:42
  • Buy why? The OP is asking how to check if the value is defined or not null. They didn't say anything about also checking if it's an empty string. – kinakuta Nov 15 '12 at 06:44
  • But I guess that is what he/she actually wants. Checking if sideBar has a useful value or not. If the empty String needs extra treatment then I would add an `sideBar !== ""`. – Juve Nov 15 '12 at 06:46
  • Did I miss the OP actually saying this somewhere else? It's certainly not communicated in the original post. In fact, it's pretty specific: "I want to check if sideBar is defined and not null in an if statement" – kinakuta Nov 15 '12 at 06:47
2

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

xgqfrms
  • 10,077
  • 1
  • 69
  • 68
1

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.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • Hi. Can you comment on Y_s's suggestion. Would it be better to use === ? –  Nov 15 '12 at 06:08
  • @Marilou It would probably be better. === is the strict equality operator. I'll edit with strict comparisons. JavaScript is weird in that it has two equality and strict equality, that's not the case with most languages. – evanmcdonnal Nov 15 '12 at 06:11
1

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".

Dane Balia
  • 5,271
  • 5
  • 32
  • 57
  • 1
    It would check for 0, NAN, Empty String and for "false" :) – Dane Balia Nov 15 '12 at 06:09
  • But 0 is a valid value. Your check would return false. – kinakuta Nov 15 '12 at 06:11
  • Not sure if that's what he is looking for. But I do appreciate your point, though falsey could be legitimate in the certain situations. But that is the reason why 0, ' ', NULL, undefined are grouped, cause by programmatic design they are falsey. – Dane Balia Nov 15 '12 at 06:20
  • 1
    Right, but if you're checking specifically for definition or null, checking for truthiness can be hazardous. – kinakuta Nov 15 '12 at 06:23
  • The value will not be `0` since `localStorage.getItem` returns a `String` or `null`. (see my answer) – Juve Nov 15 '12 at 06:32
  • You answer suffers from the same problem - in this case, an empty string is a valid value to set a variable to, which means it's not undefined, nor is it null – kinakuta Nov 15 '12 at 06:41
  • you arguing over semantics, and you are veering away from the original question. The suggestion I gave resolves the question stated, null or undefined. – Dane Balia Nov 15 '12 at 07:03
  • That's simply not true - with JavaScript, how you check if a variable is defined or not null (what the original question is asking) should not be done by checking for truthiness. – kinakuta Nov 15 '12 at 07:22
  • This method is giving wrong result in some situations. Don't use it! – Iman Sedighi Aug 04 '14 at 10:18
0

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

y_s
  • 138
  • 4
0

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).

MikhailRatner
  • 452
  • 6
  • 13