JavaScript .setItem()
Published Aug 2, 2023
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.
Syntax
localStorage.setItem(key, value);
sessionStorage.setItem(key, value);
Both key and value are required parameters.
- The
keyis the name of the key to create. - The
valueis the value to create/update thekey.
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:
undefinedGender : male
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