0

I want to check if the window.sessionStorage object exists. Is this the way to do it:

if (window.sessionStorage)

in javascript?

2
  • That's a way to check if the property isn't a falsy value, it could be any truthy value including objects. Commented Jan 5, 2016 at 23:59
  • Unless you really did want to check whether there were no items in sessionStorage (which is not common; you should probably check for specific keys instead), use what you have in the question and not what was written in the answers. Commented Jan 6, 2016 at 0:50

3 Answers 3

1
if(sessionStorage.length == 0) {
    //do something
}

That will validate whether sessionStorage is empty or not. Alternatively, you can use this:

if(typeof(sessionStorage) == 'undefined')  {
    //do something
}
Sign up to request clarification or add additional context in comments.

1 Comment

The first check here could possibly fail, since if sessionStorage didn't exist on the global object, there would be an exception.
0

Use can use modernizr to check session/web storage and other browser features.

In case you can't add the lib, check how they handle it here

Cheers.

Comments

0

Your proposed solution will work since we know that the sessionStorage property must refer to an object—and objects always resolve truthy in expressions.

However a word of caution, when checking for the existence of any arbitrary property in JavaScript (where we don't necessarily know the value), it's safest to check that the key exists in the object of interest. For example:

var exists = (someObject && 'someProp' in someObject);

We need to do this because someProp could be a valid property yet the test would fail when equal to: false, "", 0, or any other value that would be falsey in an expression.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.