2

This line

item = JSON.parse(localStorage["item"]);

caused an error in my console showing Uncaught SyntaxError: Unexpected end of input when my localstorage has no value? How do I resolve this issue? I know that empty string is not a valid json.

4
  • 3
    because an empty string is not valid json Commented Jun 1, 2015 at 2:45
  • @PatrickEvans Thanks for clarify that, but how to resolve this issue? Commented Jun 1, 2015 at 2:47
  • Easy test to see if the string is empty first, if it is dont parse Commented Jun 1, 2015 at 2:47
  • @PatrickEvans localStorage["item"] !== "" ? JSON.parse(localStorage["item"]); correct? Commented Jun 1, 2015 at 2:49

1 Answer 1

0
if(localStorage["item"]){
  item = JSON.parse(localStorage["item"]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

It will only assign the variable if the "item" key exists in localStorage. You may want to set item to null, or another value that is safe for your code, in the event the key doesn't exist (a ternary would be a clean way to do it).
Code without an explanation is rarely helpful.

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.