JavaScript setItem()

Beginner
6 min read
Updated: Nov 2026

Definition and Usage

storage.setItem(key, value) stores a string value under key. Non-strings are converted with ToString.

JavaScript Syntax

JavaScript
const store = new Map();
const storage = {
  setItem(k,v){store.set(k,String(v));},
  getItem(k){return store.has(k)?store.get(k):null;},
  removeItem(k){store.delete(k);},
  clear(){store.clear();},
  key(i){return [...store.keys()][i]||null;},
  get length(){return store.size;}
};
storage.setItem("user", "Ada");
console.log(storage.getItem("user"));
Try it Editor

How It Works

  1. setItem. Writes the pair.
  2. getItem. Confirms.

Examples

Example 1 — Store JSON

Serialize objects.

JavaScript
const store=new Map();
const storage={setItem(k,v){store.set(k,String(v));},getItem(k){return store.has(k)?store.get(k):null;}};
storage.setItem("u", JSON.stringify({id:1}));
console.log(JSON.parse(storage.getItem("u")).id);
Try it Editor

How It Works

  1. stringify on write.
  2. parse on read.

Frequently Asked Questions

Browsers may throw QuotaExceededError when storage is full.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful