Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
How to set localStorage variables properly

What is the proper way to set a variable in localStorage?

localStorage.hello = 'world'

or

localStorage.setItem('hello','world')

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!