• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

108
Views
JSON.parse an Undefined object from Local Storage

I am having a LocalStorage item which I am parsing into a variable like this:

let resp = JSON.parse(localStorage.getItem('someKey'));

The thing is sometimes, the localStorage may not have the value and it may return an Undefined object to parse which is resulting in following error:

SyntaxError: Unexpected token U in JSON at position 0

I have tried this:

let resp = localStorage.getItem('someKey') ? JSON.parse(localStorage.getItem('someKey')) : null;

But I believe this is not very optimal way of handling this, any suggestions are welcome

almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

your solution is just fine, if you want it to be shorter, you could try this

let resp = JSON.parse(localStorage.getItem('someKey') || null)

Here is how it works:

  1. localStorage.getItem('someKey') || null will evaluate the left side of the code first, if localStorage.getItem('someKey') returns undefined or '' empty string, it will return the right side code which is null

  2. Then, JSON.parse(null) will return null instead of error

almost 3 years ago · Juan Pablo Isaza Report

0

You could try something like this:

let resp = null;
const storedResp = localStorage.getItem('someKey');
if (storedResp) {
  try {
    resp = JSON.parse(storedResp);
  } catch (e) {}
}

This shouldn't generate any errors since you're only parsing it to JSON if it exists, and then catching any errors if JSON parsing fails. You're left with resp being equal to null or the stored data as JSON, with no errors in any case.

As others have said, your current solution is fine, but there are two potential issues with it as written:

  • You access the item in localStorage twice, which may be unnecessarily slow if it is a large object.
  • Many companies prefer (or require) that you wrap lines at 80 characters and your current solution is 96 characters long.
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error