Let’s say we have two files - A.js and B.js.
I had this challenge where I had to find some way to obtain a value of a variable from one A.js file and use the value of variable in B.js file. I also had the limitation where I couldn’t merge A.js with B.js. It wasn’t practical to make a third file placing the common parts of codes from A.js and B.js into it.
Then, I figured out something called Local Storage. With local storage, web applications can store data locally within the user's browser.
Earlier, the application data was stored on cookies in every server request, provided the storage limit of cookies is small as compared to the storage limit provided by local Storage
Local storage is more secure, and large amounts of data can be stored locally without affecting website performance, and the information is never transferred to the Servers.
All pages can store and access the data stored in Local Storages.
The implementation and use of Local Storage is shown below.
- My A.js and B.js files have 2 variables named variableOne and VariableTwo with values “valueOne” and “valueTwo” respectively.
- A.js var variableOne = "valueOne";
- B.js var variableTwo;
- We need to get the value from variableOne from A.js and set it in variableTwo in B.js.
First, we will store the value of variable “variableOne” from A.js in local storage.
(Below is the code written in A.js)
- localStorage.setItem("vOneLocalStorage", variableOne);
- We will obtain the value of variable “variableOne” from Local Storage.
In the localStorage, the value is stored in the variable “vOneLocalStorage”.
So, the Get method includes mentioning the localStorage variable, as shown below.
(Below is the code on B.js)
- var vOneLS = localStorage.getItem("vOneLocalStorage ");
- And the final copy which will indicate the Value of variableOne is moved to variableTwo.
- var variableTwo = vOneLS;
Working with Local Storage is quiet tricky when you store Boolean or number values inside local storage.
Let’s check both the scenarios.
- When you store a Boolean value in local Storage, the Boolean value is changed to string.
Check below.
- var booleanValue = false;
- localStorage.setItem("trueORFalse ", booleanValue);
- booleanValue = localStorage.getItem("trueORFalse");
Now, the BooleanValue is “false” i.e. converted to string.
So, to get through such problems do convert the string to Boolean.
Keeping it simple.
- if (booleanValue == "false") booleanValue = false;
- else booleanValue = true;
So, apply the above check when dealing with Boolean values in local Storage.
- When you store a Number value in local Storage, the Number value is changed to string.
Check below.
- var number = 123;
- localStorage.setItem("numberLS", number);
- var value = localStorage.getItem("numberLS");
Now, the numberLS is “123” i.e. converted to string.
So, convert the string into number using the below code.
- var result = Number(value);