简体   繁体   中英

null or undefined check in javascript

I am caching a string in my localStorage

 checkLoop:function(){   //function is hit only if internet is connected
 localStorage['key'] = "Some string response from web service";
 //JSON Web service could return null, "" (empty response) too
 }

This key would be defined only when there is internet connection. So there are chances that my function checkLoop is never been hit. ie localStorage is never defined.

Later I have a check to see if it is defined or null

So making a check like if(!localStorage['key']){..//TODO..} would work?

Or I need to customize it more for better code?

if(!localStorage['key']){
    // Will enter if the value is null\undefined\false\0\""
}

You might want to use this instead:

if(localStorage['key'] == null){
    // only null\undefined.
}

DEMO

Falsy values in javascript are:

  • undefined
  • null
  • false
  • 0
  • "" - (Empty string)

Use typeof

if(typeof localStorage['key'] !== 'undefined'){ 
    // Do Something 
}

Note: This is useful if you want to store false or 0 values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM