Reputation: 19423
What is the proper way to set a variable in localStorage?
localStorage.hello = 'world'
or
localStorage.setItem('hello','world')
Upvotes: 5
Views: 479
Reputation: 370729
The method used is very unlikely to matter. The standard lists that the following methods are equivalent:
storage.setItem (key, value) storage[key] = value
Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
Very unusual situations in which setItem
and getItem
would be preferred over dot notation assignment or retrieval would be when properties on the prototype might be referenced - such as with .length
and .__proto__
. (But dynamic storage keys are a pretty bad idea - better to organize them into their own array or object in a single storage key instead. If the keys aren't dynamic, such collisions shouldn't occur in sane code, unless someone forgot that length
is reserved)
For an example of a problematic use of length
with dot notation:
localStorage.length = '123'
console.log(localStorage.length)
will not give you 123
, but the number of keys in storage. (The assignment silently fails.) On the other hand, using setItem
and getItem
with length
(or any other arbitrary string) will work.
getItem
and setItem
are also more compatible with type-checking systems like TypeScript and Flow than dot notation.
Personally, when I'm not using TypeScript, and when the storage key is static, I use dot notation because it's more concise and doesn't cause any problems.
Upvotes: 5