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

后端 未结 6 1434
难免孤独
难免孤独 2021-02-05 11:35

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

6条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 11:48

    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
    }
    

提交回复
热议问题