Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda