What should I check for when writing a function to check if a key/value pair already exists in the Local Storage object? If there is no such key/value pair will it return null
, an empty object, something else?
Asked
Active
Viewed 816 times
-7

Peter David Carter
- 2,548
- 8
- 25
- 44
-
Of course there's a short way for any falsy : `if (!storyStage)`. – Shikkediel Nov 21 '15 at 12:35
-
It will return whatever it returns when you try it. – Nov 21 '15 at 13:15
-
Possibly because you could have found the answer by simply trying it, or by reading the documentation. – Nov 21 '15 at 13:16
-
1Don't put answers in the question, that's certainly not going to help you avoid downvotes. – jonrsharpe Nov 21 '15 at 13:18
-
Ok, I didn't know that. That's why I asked the question about it in Meta :). – Peter David Carter Nov 21 '15 at 14:05
-
Lemme time myself finding out...It took 17 seconds for me to 1) open the dev console 2) type in `localStorage.getItem('foo')` and see 3) `null` be written in the console. People often say, "there are no stupid questions." I don't believe that is true. Stupid questions are the ones *that waste your **own** time when you ask them.* This whole *frustrating* process--your writing the question, dealing with comments, waiting on an answer, answering it yourself, and taking it to Meta--has wasted **so much** of your own time. Seventeen. Seconds. – Nov 24 '15 at 17:35
-
The question is not too broad and should not have been closed. – Peter David Carter Mar 18 '16 at 18:30
1 Answers
4
localStorage.getItem
will return null
for keys that are unset:
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.
Source: https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-getitem

Wander Nauta
- 18,832
- 1
- 45
- 62
-
-
That's true - I usually prefer to use `getItem` because it also works when your key happens to be "length" (see [here](https://stackoverflow.com/questions/12632463)) – Wander Nauta Nov 21 '15 at 13:30