# How to Use localStorage in JavaScript

You know when you accidentally close a form just before you're done filling it out, and when you reopen the page, all your info is still there?  
That’s localStorage at work.

localStorage is a feature in JavaScript that allows developers to store data directly in the browser. In this article, we’ll look at what localStorage is (and what it isn’t) and walk through a quick demo on how to use it.

### **What local storage is and isn’t**

localStorage is a built-in feature of modern browsers that lets you store data with **no expiration**. That means the data stays saved in the browser until it’s manually cleared either by your code or by the user.

That data is only stored on the specific browser and device where it was created. So, if you log into the same app on a different browser or phone, don’t expect your localStorage data to follow you. It’s not synced or tied to any user account.

### **How does local storage work?**

* **To set an item:**
    
    ```javascript
    localStorage.setItem("myCat", "Tom");
    ```
    
* **To get an item:**
    
    ```javascript
    localStorage.getItem("myCat");
    ```
    
* **To remove a specific item:**
    
    ```javascript
    localStorage.removeItem("myCat");
    ```
    
* **To clear everything:**
    
    ```javascript
    localStorage.clear();
    ```
    

### Save and Retrieve Data Using localStorage

Open your DevTools (right-click → Inspect → Console tab) and try this:

Start by saving something:

```javascript
localStorage.setItem("username", "bridget");
```

Nothing happens, it just runs. But behind the scenes, your browser has stored the word `"bridget"` under the name `"username"`.

Now let’s check if it worked:

```javascript
localStorage.getItem("username");
```

You should see:

```javascript
"bridget"
```

That means it worked. The value is saved in your browser.

Now let’s remove it:

```javascript
localStorage.removeItem("username");
```

And try to get it again:

```javascript
localStorage.getItem("username");
```

This time, you’ll get:

```javascript
null
```

That’s the browser telling you: “There’s nothing stored with that name anymore.”

You can also overwrite a value anytime by using `setItem` again with a different value:

```javascript
localStorage.setItem("username", "you");
localStorage.getItem("username");
```

Now the saved value is `"you"` instead of `"bridget"`.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1752490263228/0a6d111a-da79-4664-994a-e4c28d46c638.png align="center")

### **Conclusion**

localStorage is super useful for keeping small pieces of data on the browser things like form inputs, theme preferences, or draft content. It’s not a replacement for a database, but it’s a great tool for quick, lightweight storage.

You’ve seen how easy it is to use just a few lines of code, and your site becomes a bit more user-friendly.  
Play around with it. Try storing more values. You’ll get the hang of it fast.
