I am new to Javascript, is there a way to store data in an array and be able to access it later. Example :
I have created an array
If I click on my HTML file button (add a question), a function generates a random Id for a question block (like id="13819").
It is then added to an array of question Id's
Once the function is done running, does the Id stay in the array once added? Or does the array reset when the function called again?
If it does reset, how do you make it to not reset?
It depends on where your variable is created. If it is a top level variable(global) you will be able to add new data during the whole users session. On the other side if that variable is created inside a function it will be erased every time you call that function.
Short answer: Yes
Long answer: It depends
It depends on where you created the array. This is known as the scope of the array.
If it is inside the function, the scope of the array is inside the function, so only things inside the function can access the array. Once the function is finished, the array no longer exists.
You can create it in the global scope, i.e. as an attribute of the global window object, but you should try as much as possible to limit the scope of your variables, so that you don't pollute the global namespace
Related
I've recently read about closures in javascript and if I understand it correctly, it's when an inner function has access to variables in an an outer function. If so, under what use cases should I be using closures?
When you're thinking about writing a function, but realize that that function needs to do some internal state-keeping to determine its actions. The state should be stored, read and modified in a variable — but you don't want that variable existing outside of the function (if other functions can tamper with this function's state, things could go wrong), and at the same time you can't define the variable inside the function because each time you call it that variable would be reset.
A closure is effectively simply for locking variables in an immediate scope. The easiest example is probably a toggle:
var lightSwitch = ( function closure(){
var isLightOn = false;
return function flickLightSwitch(){
isLightOn = !isLightOn;
alert( isLightOn );
}
}() );
Imagine you're in a badly lit room, where you can't tell if the light is on or off except by flicking the switch to see the difference. When the code is executed, the closure function runs immediately, assigning the value false to isLightOn and assigning the function flickLightSwitch to the variable lightSwitch at the top. Now whenever the flickLightSwitch function is executed (called by the variable it's assigned to, lightSwitch), isLightOn becomes the opposite of whatever it used to be, and the user is alerted of its new value. External code can't read or modify the value of isLightOn because it's 'locked' in the closure function.
function exampleFunction(){
var theVariable = "Lol!";
var variable2 = Lol.toLowerCase();
console.log(theVariable);
delete theVariable; //to prevent bugs, I want to ensure that this variable is never used from this point onward.
console.log(theVariable); //This still prints "Lol!", even though I just tried to delete the variable.
}
In JavaScript, is it possible to prevent a variable from being used in a function after a certain point? I've tried declaring a string called theVariable, and then I tried to delete the variable using delete theVariable, but console.log(theVariable) still prints theVariable's value even after that point.
I tried using delete theVariable to make theVariable unusable from that point onward (in order to prevent myself from accidentally using the variable when it is no longer needed), but it doesn't appear to have that effect. Is there any way to work around this limitation?
One way is to limit its scope. Since JavaScript doesn't have block scope, that requires an IIFE (or similar technique):
function exampleFunction(){
var variable2;
(function() {
var theVariable = "Lol!";
variable2 = Lol.toLowerCase();
console.log(theVariable);
})();
// theVariable is now out of scope, and cannot be referenced
}
In that case you can set the value to undefined like theVariable = undefined
The delete function does not work as you expected
From docs
The delete operator removes a property from an object.
In this case theVariable is not a property of an object, it is a variable in the current function scope.
You cannot delete primitive types, only objects. If you don't want to use a variable after a certain point, just review your code so that you don't use it. Unfortunately, JS does not have block scoping to restrict the visibility of variables. You'll have to check for this manually.
Alternatively, set the value to undefined.
I've created a JavaScript Class just as following:
function MyClass() {
this.myProp = '';
}
MyClass.prototype.myTestFunction = function() {
alert('test');
}
Now, I instantiate this class.
var myTestInstance = new MyClass();
myTestInstance.myTestFunction();
This outputs an alert with 'test'.
Now I want to have the variable name 'myTestInstance' into the function 'myTestFunction()' without having to pass it as a parameter.
Is it somehow possible to find out the variable name of the instance from inside the called function?
Thank you for your help!
EDIT: Just to add information why I would need this: Every instance I create in my real project is a special HTML table. In the header fields are sort-buttons for every column. Therefore I added dynamically a link-element with href='javascript:myTableInstance.sort()'. To print this dynamically IN the instance, I needed the variable name.
Would there be another, better solution?
No, it does not make sense in any way. First of all, instance is not tied to a single variable (it might be referenced by many variables, it could be referenced by none - perhaps as a member of some array) - so the question "what is the name of the variable that stores the instance" is unanswerable. Secondly, the scope of myTestFunction and myTestInstance could be very different. In a usual case myTestFunction would not "see" the scope that has myTestInstance defined - so knowing the name of the variable would not help.
You should just use "this" inside myTestFunction.
When the user leaves the singup part of the page..the global is no longer needed.
How do I get rid of it..so it does not waste memory?
it is declared in the global namespace as follows:
var local =
{
client_validation:1,
persistent_element:'hide_1'
};
I'm not sure what you mean by "How do I have a global variable that is used for only one of two pages". Global variables are only "global" within the current page. If you navigate to another page they automatically disappear along with everything else on the page you are leaving.
Anyway, if you have some data structure using up memory you can allow the garbage collector to reclaim the memory if you remove all references to the structure.
In your case, either of these statements should do it:
global.page_var = null;
// or
delete global.page_var;
(Assuming you don't have other variables or closures with their own references to the same data structure.)
Assuming you can still access the variable, this should take care of it:
if (page_var){
page_var = null;
}
Basically i want to load JS file like this into the page dynamically
globalVar = "some variable";
alert(globalVar);
And then i want to remove it, i can easily delete script from DOM, but i will have globalVar remain in the memory...
Is there a JS libraries that will help me to load script and then unload it and unload all variables, classes, functions that were declared by that script? Or is there some tricks to do that?
In JavaScript, when you declare a global variable it is actually a property of the "global" object (usually the DOMWindow, or "window"), so you can simply delete the property by the name of the variable to delete the global reference. For example:
var foo = 123;
alert(foo); // Alerts "123"
alert(window.foo); // Alerts "123"
delete window.foo;
foo; // ReferenceError: foo is not defined.
So if you can keep track of the global variables you use (which should be very, very few, like one) you can just delete it as a property from the "window" or "global" root-level objects.
Update
You can extend this idea to work generally as follows. At the beginning of your script, enumerate the properties of the global object and store them in a reference object. Then, when you want to identify newly added globals, enumerate the global properties again and store only the ones which do not exist in the reference object (meaning they were newly added since you last checked). Then simply delete these additional properties.
This is horrible JavaScript. If the JS you're importing doesn't do anything to the global object that is worth keeping around when you remove it (for example changing the DOM), then it shouldn't be writing new variables to the global object at all.
Hopefully you have control over the imported JS, and should encapsulate the code in a self-executing function and ensure that all variable declarations start with var. This means you're not polluting the global object with your own variables and you can do whatever you need to in the script. Your code above would become:
function() {
var globalVar = "some variable";
alert(globalVar);
}();
This will ensure that no new variables are written to the global object, and you still have access to them to change them (which presumably you need to do).
If you want more info, could you shine some more light on what the important script actually does?