Ollie
Ollie

Reputation: 57

Are JS variables destroyed when a new html page is loaded?

just a quick question. When you have a js file that contains your normal functions, variables and other stuff, that page is loaded and then used as and when code is needed. But my question is, what happens to any/all variables that you created when, for example, you navigate to another page (like using window.location.href)? Do they still exist in memory? are they somehow still accessible? Or are they gone for good until you reload the original file?

Cheers

Upvotes: 1

Views: 797

Answers (1)

Mukul Kumar Jha
Mukul Kumar Jha

Reputation: 1082

Short ans: Yes.

Every variable stored in your JS file are lost , or to say , a new copy is created for each page reload or on change of Window.location.href.

To persist the data or to use the value of variable between reloads you should be using client-side data storages, like sessionStorage or localStorage or cookies.

For example lets say to use value of persist variable you can use

let persist = "My data";
// Store it in localstorage 
localStorage.set('persist', persist);

// Get the value of your saved variable to use it elsewhere 
let persist = locastorage.get("persist");

//To delete the variable from storage 
localStorage.removeItem('persist')

// To clear the entire storage
localStorage.clear()

Syntax is same with the sessionStorage But values stored with sessionStorage are available for the duration of the page session only . For more info on DOM storage you can read here.

Upvotes: 3

Related Questions