Cast "null" as null in javascript
Asked Answered
P

5

7

I use the session storage to set a key that can take numeric values or null. I noticed that the field is stored as a string no matter what I put in. Is there a nice way to convert back my stored value to null ?

For instance, I want to do a check in my code as such:

if (!sessionStorage.getItem('key')) {
   // do something
}

Whats the best way to make that check? The obvious way would be

 if (!sessionStorage.getItem('key') !== "null") {
       // do something
 }

I am wondering if there's an alternative.

Payment answered 10/3, 2016 at 21:28 Comment(4)
Why don't you just use sessionStorage.removeItem('key') instead of sessionStorage.setItem('key','null')?Cutcherry
For my use case, it's easier to manage. I have a dropdown menu to change set the value for key. it's binded to an event listerner, so it would be odd in one case to do a delete and in all other case to set the value no?Payment
localStorage only stores strings, it has no concept of JavaScript types, so you should actually be checking for a specific string, be it null, not set, 0 or whatever you choose, or just remove the item and check that it's not set.Outdoor
I actually think checking to see if it is a null string is the best way. Unless you wrap it in try ... catch, parsing would throw an error if you try to JSON.parse().Canna
C
2

I just want something that would evaluate to false

You could use an empty string instead to mark the unset value:

sessionStorage.setItem('key','');

This way you can re-use your current check:

if (!sessionStorage.getItem('key')) {
   // do something
}

That said, you mentioned you had a drop down to select values, and that's why you need such a value, but I think a solution involving deleting the item on the null value would be better. Here's a working demo, and the code used to make it:

var dd = document.getElementById('dropdown');

dd.addEventListener('change', function(){
  var value = this.value;
  if (value === 'null')
    sessionStorage.removeItem('key');
  else sessionStorage.setItem('key', value);
});

var check = document.getElementById('check');
check.addEventListener('click', function(){
    this.innerHTML = 'Value: '+sessionStorage.getItem('key')+
                     ', check: '+(!sessionStorage.getItem('key'));
});
<select id="dropdown">
  <option value="null">none</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>

<button id="check">Check value</button>
Cutcherry answered 10/3, 2016 at 21:35 Comment(0)
S
13

You can parse it

JSON.parse('null') // null
JSON.parse('1')   //  1

so

var val = sessionStorage.getItem('key');
val = JSON.parse(val);

Close to cast

Alternative would be:

var val = sessionStorage.getItem('key');
val = val*1 || null;
Stouthearted answered 10/3, 2016 at 21:30 Comment(4)
Would work in those two cases, but what if the value is a String? JSON.parse("Hello"); does not work.Prognostication
@Prognostication he stores numbers or null that's what was describedStouthearted
Gotcha. I missed that part. Guess this is a nice, working, hack then.Prognostication
JSON parsing is an overkill for this.Cutcherry
N
2

Serialize your value as JSON before writing it to storage.

var json = JSON.stringify(val);

Then parse it when you read it out again.

try {
  var val = JSON.parse(storage.item);
} catch(ex) {
  // handle errors
}

It's important to wrap the parser in a try block. If the user or the browser clears the session storage, then you'd be trying to JSON.parse('undefined') which will throw an error.

Newsprint answered 10/3, 2016 at 21:33 Comment(0)
C
2

I just want something that would evaluate to false

You could use an empty string instead to mark the unset value:

sessionStorage.setItem('key','');

This way you can re-use your current check:

if (!sessionStorage.getItem('key')) {
   // do something
}

That said, you mentioned you had a drop down to select values, and that's why you need such a value, but I think a solution involving deleting the item on the null value would be better. Here's a working demo, and the code used to make it:

var dd = document.getElementById('dropdown');

dd.addEventListener('change', function(){
  var value = this.value;
  if (value === 'null')
    sessionStorage.removeItem('key');
  else sessionStorage.setItem('key', value);
});

var check = document.getElementById('check');
check.addEventListener('click', function(){
    this.innerHTML = 'Value: '+sessionStorage.getItem('key')+
                     ', check: '+(!sessionStorage.getItem('key'));
});
<select id="dropdown">
  <option value="null">none</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>

<button id="check">Check value</button>
Cutcherry answered 10/3, 2016 at 21:35 Comment(0)
P
0

The sessionStorage is a key-value database where both are store as strings. You can see the documentation stating DOMString for both Storage.setItem() and Storage.getItem().

The nature of this is then that the objects you retrieve will always be strings. You will have to cast them manually, either by applying JSON.parse() or a completely manual approach. There is no way to get back the null without any operations.

Another approach that has been mentioned is simply to avoid storing null values in the sessionStorage. It is easier to check if a key exists than to cast it correctly afterwards.

Prognostication answered 10/3, 2016 at 21:32 Comment(2)
Ok obviously I am expecting to do an operation. It seems JSON.parse is the way to go. Actually in my case, I just want something that would evaluate to false.Payment
Technically, you could also eval it.Newsprint
S
-1

Since the returned statements are in strings you can say if(!sessionStorage.setItem('key','')) {}

Ser answered 10/3, 2016 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.