Home > database >  Why JavaScript null check doesn't working?
Why JavaScript null check doesn't working?

Time:06-04

function readProperty(property)
{
  console.log(localStorage[property]) //Alerts “null”
  if(localStorage[property] == null)
  {
      console.log('Null chek')
      return false;
  }

  return localStorage[property];
}

log outputs "null", but 'if()' doesn't work. I try with ===, its not work too. Help please.

UPD: Thanks everyone this change helped me if(localStorage[property] == 'null')

CodePudding user response:

The keys and the values stored with localStorage are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Try:

localStorage[property] === 'null'

CodePudding user response:

Although: console.log(localStorage[property]) may report null, the actual value is undefined.

So, in your if statement, if you test against undefined, you'll get a match.

Better yet though, just test for the existence or non existence of a value with:

 if(localStorage[property])...  // Tests for any "truthy" value

or

 if(!localStorage[property])...  // Tests for any "falsey" value

CodePudding user response:

Well, I don't know if you're trying to use the global localStorage or if it's a defined variable in your code.

If you're using the localStorage API, you should check if a key exists like this...

if (!localStorage.getItem("my-item")) {
  console.log("item doesn't exist.");
}

The .getItem() method returns null when the key isn't defined so checking using ! or item !== null work.

.getItem() reference from MDN, https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem.

CodePudding user response:

you have to get item from localStorage using getItem() function like that

if(!localStorage.getItem(property) || localStorage.getItem(property)===null){
   // there is no item in localStorage with the property name 
}
  • Related