localStorage.key
Returns the name of the nth key in the localStorage, or null if the index is out of range
Syntax
localStorage.key(index)Parameters
| Parameter | Type | Description |
|---|---|---|
| index | number | The zero-based index of the key |
Return Value
The key name string, or null
Examples
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
console.log(key, localStorage.getItem(key!))
}function getAllKeys(): string[] {
const keys: string[] = []
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (key) keys.push(key)
}
return keys
}const firstKey = localStorage.key(0)
console.log('First key:', firstKey)Understanding localStorage.key
The localStorage.key method in JavaScript returns the name of the nth key in the localStorage, or null if the index is out of range. 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.key(index). It accepts 1 parameter: index. When called, it returns the key name string, or null. Understanding when and how to use key() helps you write more expressive, readable code.
Common use cases for localStorage.key include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like localstorage-getitem, localstorage-length, localstorage-setitem, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for localStorage.key 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
localStorage.getItemReturns the value associated with the given key in the localStorage object, or null if the key does not exist
localStorage.lengthReturns the number of key/value pairs currently present in the localStorage object
localStorage.setItemAdds a key/value pair to the localStorage object, or updates the value if the key already exists
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.