Storage

localStorage.setItem

Adds a key/value pair to the localStorage object, or updates the value if the key already exists

Syntax

JavaScript
localStorage.setItem(key, value)

Parameters

ParameterTypeDescription
keystringThe name of the key
valuestringThe value to store

Return Value

undefined

Examples

Basic Usage
localStorage.setItem('theme', 'dark')
console.log(localStorage.getItem('theme')) // 'dark'
Practical Example
const user = { name: 'Alice', role: 'admin' }
localStorage.setItem('user', JSON.stringify(user))
Advanced Usage
function savePreferences(prefs: Record<string, string>) {
  Object.entries(prefs).forEach(([key, val]) => {
    localStorage.setItem(`pref_${key}`, val)
  })
}

Understanding localStorage.setItem

The localStorage.setItem method in JavaScript adds a key/value pair to the localStorage object, or updates the value if the key already exists. It belongs to the Storage object and is one of the most widely used methods for working with storage values in modern JavaScript and TypeScript applications.

The method signature is localStorage.setItem(key, value). It accepts 2 parameters: key, value. When called, it returns undefined. Understanding when and how to use setItem() helps you write more expressive, readable code.

Common use cases for localStorage.setItem include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like localstorage-getitem, localstorage-removeitem, localstorage-clear, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for localStorage.setItem is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More Storage Methods

Other methods in the Storage object

Related Tools

More Storage Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.