Alan2
Alan2

Reputation: 24602

How can I make the value be equal to localstorage or default to "0"

I am getting a value like this:

CreatedBy = localStorageService.get('selectedCreatedBy');

How can I make it default to "0" if there is nothing in local storage?

Upvotes: 1

Views: 391

Answers (3)

Rob M.
Rob M.

Reputation: 36541

Here is an extremely simplified version of a localStorage wrapper library I wrote a year ago that allows default values to be passed (also does JSON encoding/decoding of values). Outside of using something like this you are going to have to check each time you retrieve a value from localStorage that the value is not null as the other answerers have pointed out.

var storage = {
    get: function(key, default_value){
        var response = localStorage.getItem(key);
        response = response || default_value || null;
        if(response){
            try{
                response = JSON.parse(response);
            } catch(e) {}
        }
        return response;
    },
    set: function(key, value){
        if(typeof value.charAt !== 'function'){
            value = JSON.stringify(value);
        }
        localStorage.setItem(key, value);
        return this;
    }
}

storage.set('foo', {a: 'b', c: 'd'});

storage.get('bar'); // returns null
storage.get('bar', [1, 2, 3]); // returns array [1,2,3]
storage.get('foo'); // returns Object {a: "b", c: "d"}

Upvotes: 0

qiu-deqing
qiu-deqing

Reputation: 1333

var value = localStorage.getItem("key");

var result = value === null ? 0 : value;

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage

see definition of localStorage.getItem(), if the value is not stored. getItem() return null

Upvotes: 1

Ankit Tyagi
Ankit Tyagi

Reputation: 2375

have you try like this :

CreatedBy = localStorageService.get('selectedCreatedBy') || 0;

Upvotes: 1

Related Questions