Using Variable Values From One JavaScript File To Another JavaScript File Using Local Storage (Get And Set)
Using variable value from one JavaScript file in another JavaScript file.
For instance you have two files => app1.js and app2.js. It came to my mind once, I had this challenge where I had to come with a way to obtain a value of a certain variable from the app1.js file and use the value in app2.js file, I was also limited to not merge the two files and I couldn't practically create a third file to combine the two files.
Then I figured out how to use the Local Storage to solve the issue.
In the Local Storage web application's can store a large amount of data locally without affecting the website performance, this information is more secure and is NEVER transferred to the servers. Applications data used to be stored on cookies in every server request since cookie storage is limited not as compared to the Local Storage many website's pages opt for it.
Below is how I implemented the use of Local Storage;
My app1.js and app2.js files contain 2 variables named varOne and varTwo with values “valueOne” and “valueTwo” respectively.
app1.js var varOne = "valueOne";
app2.js var varTwo;
I had to get the value varOne from app1.js and set it in varTwo in app2.js.
- First, I had to store the value of variable "varOne" from app1.js in local stotage (Below is the code written in app1.js)
localStorage.setItem("varOneLocalStorage, varOne"
In the localStorage, the value is stored in the variable "varOneLocalStorage"
2. By the using the get method I had to mention the localStorage variable; (The code belongs in app2.js)
var varOneLs = localStorage.getItem("varOneLocalStorage");
3. This final copy indicated the value of varOne which is moved to varTwo.
var varTwo = varOneLs;
Working with Boolean values in the Local Storage is kinda tricky since the Boolean values need to be changed to a string (Check below)
var booleanValue = false;
localStorage.setItem("trueORFalse ", booleanValue);
booleanValue = localStorage.getItem("trueORFalse");
Now, the BooleanValue is “false” i.e. converted to string.
To avoid such problems make sure you convert the string to Boolean.
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. To convert the string into a number use the code below.
var result = Number(value);