JavaScript localStorage: The complete guide
Tags: javascript, webdev, programming, tutorial
Published: 2023-06-15 21:05:42

## Introduction

JavaScript `localStorage` is basically storage that is in the browsers `Window` Object. You can store anything in the `localStorage` and it will be persistent through page loads and even if the browser closes and reopens

`localStorage` and its related `sessionStorage` are part of the Web Storage API. We will be learning more about these below

## What is Web Storage API?

Web Storage API provides methods through which browsers can store key/value pairs of data (like Objects).

The key/value pairs stored in the web storage API are always in the form of strings. (integer keys are automatically converted to strings)

There are a set of methods provided by the Web Storage API that you can use to access, delete modify the key/Value pairs

There are two types of storage available in the Web Storage API

1. `sessionStorage`
    
2. `localStorage`
    
Dead Simple Chat allows you to easily add Chat to any web and mobile Application using powerful [Javascript Chat API and SDK](https://deadsimplechat.com/javascript-chat-api-sdk).

## What is LocalStorage?

`LocalStrorage` is part of the Web Storage API. It allows you to store persistent data (data remains on the browser reloads and when the browser is closed and reopened) in the browser `Window` Object as key/value pairs of strings.

There are five methods of localStorage and these are:

1. setItem
    
2. getItem
    
3. removeItem
    
4. clear
    
5. key
    

## Difference between sessionStorage and localStorage

Both `sessionStorage` and `localStorage` are part of the web storage api.

* The `sessionStorage` is only available till the browser is open, when the browser is closed the `sessionStorage` is deleted. (\`sessionStorage\` is available when the browser reloads but when the browser is closed sessionStorage is deleted)
    
* The `localStorage` is the persistent data even when the browser is closed the `localStorage` data remains in the browser
    
* `localStorage` can be deleted manually by the user and it is automatically deleted when the user is in an incognito window or private window and the user closes the browser
    

Both `sessionStorage` and `localStorage` provides similar methods to access and store data in the browser

Dead Simple Chat allows you to easily add Chat to any web and mobile Application using powerful [Javascript Chat API and SDK](https://deadsimplechat.com/javascript-chat-api-sdk).


We will be learning more about the `LocalStorage` methods below

## localStorage Methods

There are five methods in the `localStorage`. These methods let you store items, get Items, remove Items and clear the `localStorage`.

### 1\. setItem(): Store data in the localStorage

Using localStorage.setItem API you can store key/value pairs in the local storage. here is an example on how you can store the data.

```javascript
window.localStorage.setItem('candy name', 'Mars Bar');
```

the `candy name` is the key and the `Mars Bar` is the value. As we have mentioned localStorage only stores strings.

You can try this in the browser itself. Here is an example to storing the data in the chrome browser


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lp6gkwv9kr3c2s44kxdi.png)

There are multiple ways of storing the data in the `localStorage` using `setItem`. You can access data in the Object like way:

```javascript
window.localStorage.candyName = 'Mars';
window.localStorage['candyName'] = 'Mars';
window.localStorage.setItem('candyName','mars');
```

It is allowed but not recommended to store or access data in the object-like way because the user-generated key can by anything like `toString` or `length` or any other built in method name of the localStorage

In which case the `getItem` and `setItem` would work fine but the Object like method would fail

using Object like notation

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kj9rgbrmoi7nzv452oq2.png)

### 2\. getItem(): Retrieve data from the localStorage

Using the getItem API we can retrieve the key/value pairs stored in the localStorage

getItem() accepts a key and returns the value as a string

This would return the value as `Mars Bar`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4yzhaow9g6z2o8lm87fy.png)

using Object Notation

Using Object notation you can also access the data (although it is not recommended)

```bash
window.localStorage.candyName
returns 'Mars'
window.localStorage['candy2']
returns 'turtles'
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0g0ca08ckoofaaq9hdle.png)

### 3\. removeItem() Remove an item from the localStorage

you can remove any item from the `localStorage` using the `removeItem` method

Pass the key of the item that you need to remove to the `removeItem` method and it is deleted from the `localStorage`

```javascript
window.localStorage.removeItem('candies');
```

let's use the console to see how the removeItem works. First, we will use the length property to check how many items are in the local storage

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fdihwke8ms8oyhv6uhqu.png)

As you can see when we use the length property it shows there are 2 items in the `localStorage`. After we remove an item now there is only one item remaining in the local storage

### 4\. clear() clear the localStorage

With `Clear()` method of the localStorage API you can clear the entire localStorage and delete all the data in the localStorage

```javascript
window.localStorage.clear();
```

let us use the console to see how the clear method of the `localStorage` works

We will use the length to check for the number of items in the `localStorage`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/090nw8o5r29nsahiq2ln.png)

Dead Simple Chat allows you to easily add Chat to any web and mobile Application using powerful [Javascript Chat API and SDK](https://deadsimplechat.com/javascript-chat-api-sdk).


### 5. key() returns the n th  key in the storage

the key method can be passed any integer and it will return the key stored at the nth key in the storage Object

```bash
window.localstorage.key(index)
```

Let us use the console to see how the key works

We have put key/value pairs in the localStorage like

```bash
window.localStorage.candyName = 'Mars'
window.localStorage['candy2'] = 'turtles'
```

let us use the `length` to check for the contents of the localStorage

```javascript
window.localStorage.length
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ln6w1xj8100vvap4q66w.png)

as you know the index starts from 0. let us see what is at index 0


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/51gdh4jyqotle7399iw8.png)

and let us see what is at index 1

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qcj193vbsqetep284cqs.png)

Dead Simple Chat allows you to easily add Chat to any web and mobile Application using powerful [Javascript Chat API and SDK](https://deadsimplechat.com/javascript-chat-api-sdk).

## Storage Property

### length : number of key/value pairs stored in the local

The length is a read-only property of the `localStorage` interface. It returns the number of key/value pairs stored in the `localStorage`

```javascript
window.localStorage.length
```

We can use length property to test whether the `localStorage` is populated or not.

Uptill now we have used the length property multiple times and you might have become familier with.

Let us use the length property in different use cases to futher explore its uses. Let us open the console and see how we can use the length property

```javascript
window.localStorage.length
2
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6qvzbvffbiccrtqp5caf.png)

now the length property can also be used to check if the localStorage is empty. Let us clear the localStorage and see what happens if we use the length property

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c7n6n24ty6lhommi8wi.png)

It returns 0. hence we know if the length property returns 0 then the localStorage is empty

Dead Simple Chat allows you to easily add Chat to any web and mobile Application using powerful [Javascript Chat API and SDK](https://deadsimplechat.com/javascript-chat-api-sdk).

## Storage Event

The storage event is fired whenever a change is made to the storage Object

StorageEvent is sent to the window when a storage area the window has access to is changed within the context of another document

Storage event are events that are fired whenever a change takes place and you can listen to the storage event and make appropriate decision in your website or application.

### Constructor

`StorageEvent()`

Returns a new `StorageEvent` Object

let us use the console to create a new instance of the storageEvent()

creating a new instance of the StorageEvent

```javascript
new window.StorageEvent(keys)
```

returns

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0xgowoew3wjlnefbyeek.png)

### Instance Properties

### Keys (read only)

Returns a String that represents the key that has been changed. The key attribute is null when the change is caused by the clear() method

### newValue(read only)

Returns a String with the new value of the key that has been changed. It is null when clear() method has been used or the key has been removed

### oldValue(read only)

Returns a String with the original value of the key. It is null when a new key has been added where there was no key before

### storageArea(read only)

Returns a storage Object that represents the storage area that was affected.

### url(read only)

Returns a string with the url of the document who key is changed

## LocalStorage: Interesting facts

Here are some of the interesting facts about the localStorage

1. `localStorage` is always stored in UTF-16 string format. Integer keys are converted into string and stored in the localStorage
    
2. `localStorage` data is specific to the protocol of the browser and website. For example, it is different in HTTP and HTTPS
    
3. for documents loaded from `file` the requirements for localstorage is undefined and is different for different browsers
    
4. `localStorage` for incognito or private browsers is deleted when the browser is closed

Dead Simple Chat allows you to easily add Chat to any web and mobile Application using powerful [Javascript Chat API and SDK](https://deadsimplechat.com/javascript-chat-api-sdk).


## LocalStorage Limitations

Here are some of the limitations for `localStorage`

* Limited upto 5MB of data
    
* do not store sensitive data in `localStorage` as it can be easily accessed by  cross site scripting
    
* `localStorage` is synchronous meaning it is accessed one after the other and
    
* do not use `localStorage` as a database.
    
## Detecting localStorage: testing for availability

## Browser Compatibility

LocalStorage is compatible with all the latest browsers. Only the very very old browsers like Internet Explorer 6 or 7 do not support `localStorage`

In some situations like the user is in private window or the user is in incognito window the data would be immediately deleted when the user closes the window

The user can also disable `localStorage`

## Exceptions

`securityError`

A security error is thrown in the following cases:

* Origin is not a valid scheme/host/port tuple error. This happens when the origin uses `file:` or `data:` schemes. Many modern browsers treat `file:` origin as opaque origin. What this means is that the file or files that come from the same folder are assumed to come from different sources and could trigger CORS error
    
* The request violates a policy decision. For example, the user has disabled the use of localStorage on the browser
    

## Conclusion

In this article, I have explained the `localStorage` and its methods and how you can use `localStorage` to save data and access it, deleted it and modify it

**Note:** This article was originally written on the DeadSImpleChat Blog: [JavaScript localStorage: The Complete Guide](https://deadsimplechat.com/blog/javascript-localstorage-complete-guide/)