Prefer using localStorage.getItem to accessing the property name directly
tldrUsing
localStorage.getItemenables you to safely parse a string that may or may not exist.
We can access data from localStorage with getItem or by accessing the property directly. Both return the same data if it exists.
localStorage.getItem('username') // "ekafyi"
localStorage.username // "ekafyi"If the data does not exist, the former returns null while the latter returns undefined.
localStorage.getItem('sdfdsfsdf') // null
localStorage.sdfdsfsdf // undefinedIf we try to parse a stringified object, parsing undefined throws an error whereas parsing null gives you null.
JSON.parse(localStorage.getItem('sdfdsfsdf')) // null
JSON.parse(localStorage.sdfdsfsdf) // Uncaught SyntaxError ...Alternatively, we can use optional chaining with a fallback value. But I find getItem cleaner and more simple.
JSON.parse(localStorage?.sdfdsfsdf || null) // null