JavaScript .setItem()

manikanta528's avatar
Published Aug 2, 2023
Contribute to Docs

The .setItem() method updates the value to the specified storage object key, if it exists, else adds the key to the specified storage object and returns undefined.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

Syntax

localStorage.setItem(key, value);
sessionStorage.setItem(key, value);

Both key and value are required parameters.

  • The key is the name of the key to create.
  • The value is the value to create/update the key.

Example

This example demonstrates a basic implementation of the .setItem() method:

console.log(localStorage.setItem('name', 'mark'));
localStorage.setItem('gender', 'male');
console.log('Gender : ', localStorage.gender);

The output will be:

undefined
Gender : male

All contributors

Contribute to Docs

Learn JavaScript on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours