The storage keys and values are both typed as strings.
If the browser displays an alert when running the above code, you’ll know it’s working because the alert function has fetched the values from Web Storage.
It is possible to view objects in Web Storage using the Developer Tools’ Storage Inspector.
An Example Application
The following is a simple demonstration of an arithmetic operation on two variables in Web Storage:
var firstValue = window.sessionStorage.getItem('testValue1');
var secondValue = window.sessionStorage.getItem('testValue2');
var total = +firstValue + +secondValue;
document.getElementById("result").innerHTML = total;
For the currency converter, we first need a text box for the user to enter the exchange rate value:
This element calls a function called ‘writeExRate()‘:
myRate = document.getElementById("newRate").value;
Near the top of my HTML source, I added a second function that fetches the currently stored value and displays it whenever the page loads:
document.getElementById("result").innerHTML = localStorage.getItem('currentRate');
The main conversion function itself reads a value from an input field, and divides it by the current exchange rate value fetched from Web Storage:
var currentRate = localStorage.getItem('currentRate');
var inputValue = document.getElementById("yenValue").value;
var convertedToPound = (inputValue/currentRate);
document.getElementById("answer").innerHTML = convertedToPound;
And here is how it looks in the browser:
Substituting the Hard-Coded Values in My Application
In the head element, I declared the following global variable:
var sliderMultiplier = parseInt(localStorage.getItem('currentRate));
Here I’m using parseInt() because objects are always stored as strings, and currentRate must be typed as an integer before our conversion functions can use it. Also, the interface should obviously display the currently-stored value whenever the page loads, so the following lines are included:
And also a form that enables the user to update the currentRate value in localStorage:
Now it’s a simple matter of replacing the hard-coded exchange rate with the sliderMultiplier variable.