1

I can find if the local storage key exists or not using the if condition in the below code

    this.data = localStorage.getItem('education'); 
      if(this.data)//check if it exists or not empty
{
        console.log("Exists");
      }

If want to use if condition to find if it does not exist, how do I write that in code? I don't want to use else.

halfer
  • 19,824
  • 17
  • 99
  • 186
user2828442
  • 2,415
  • 7
  • 57
  • 105

1 Answers1

2

If this.data is undefined, than !(this.data) should work:

if (!(this.data)) { console.log("DOH!"); }

Edit: I just received a comment that raises a point. What if the key is false? It is not enough. What if the key actually exists and it is set to undefined? Then the method will fail. Thus probably it is better to use the in keyword (as described in this answer)

if (!("data" in this)) { console.log("DOH!"); }

as for example:

obj = { a: false, b: undefined }
if (!("a" in obj)) { console.log("a does not exist"); }
if (!("b" in obj)) { console.log("b does not exist"); }
if (!("c" in obj)) { console.log("c does not exist"); }

The output is

c does not exist
Matteo Ragni
  • 2,837
  • 1
  • 20
  • 34