Computer >> Computer tutorials >  >> Programming >> Javascript

How to preserve variables in a JavaScript closure function?


To preserve variables in a JavaScript closure function, do not set it to empty. Right now, the following is set to empty object each time it is called 

webLinks = {};

Use the following code to retain the value:

var webLink = function (containerId) {
   var link1 = "https://www.qries.com",
   link2 = “https://www.tutorialspoint.com”;
   var webLinks = {};
   return function(Id) {
      webLinks [id] = "My " + id;
      document.write(webLinks);
   }
})();