'Unexpected token u in JSON at position 0 while using local storage

Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at index.js:4:20.

Want to store data in local storage but it showing this error code below

var todoArr = JSON.parse(localStorage.getItem("todoLocal")) || [];


Solution 1:[1]

You need to check to see if something is there before you parse it.

Either

var todoArr = localStorage.getItem("todoLocal") ? JSON.parse(localStorage.getItem("todoLocal")) : [];

// var lsTDL = localStorage.getItem("todoLocal");
// var todoArr =  lsTDL ? JSON.parse(lsTDL) : [];

or

var todoArr = JSON.parse(localStorage.getItem("todoLocal") || '[]');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 epascarello