Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda