Lukas
Lukas

Reputation: 7734

Local Storage turns wrong or null value

I'm trying to set some value in local storage. So i do this:

if (localStorage) {

    var event = localStorage.getItem("Event");

    if (event != "undefined" || event != "null") {
        console.log(event)
    } else {
        localStorage.setItem("Event", "Event Name");
        console.log('test');
    }
}

I can't save value in local storage for the first time. It's not returns anything in else condition. Always returns null from exist check condition. Can anybody help?

Upvotes: 1

Views: 964

Answers (1)

MrCode
MrCode

Reputation: 64536

If it doesn't exist, null is returned, not the string "null", so change to:

if (event != null) {
    console.log(event)
} else {
    localStorage.setItem("Event", "Event Name");
    console.log('test');
}

From the W3 docs:

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.

Upvotes: 3

Related Questions