I know, that, for example, c++ has something like delete variable and it will be deleted from the memory. Is there something like this in JS.
For example, I have var canSendRequest = true; and after some operations I want to delete it totally from the memory. As I read, delete canSendRequest will not work properly, but I did not manage to find a properly working way. Does someone know, how to do that?
Since JS is garbage collected, you don't have direct control over the release of memory.
You just have to wait for the runtime to free the memory, which it will if there are no permanent references to it via the global object or a permanently existing closure. In those cases, you need to eliminate such references to the variable so that it qualifies to be freed.
If you're saying you want to eliminate the identifier itself from the scope, you definitely can't unless it was a global that was set as a property of the global object, not using proper variable declaration syntax.
Var is Hoisting type use let or const. like var g_a = 1; //create with var, g_a is a variable delete g_a; //return false console.log(g_a); //g_a is still 1
now try with let and const
Related
I was reading this post that clarified almost everything about scopes, leaving only this doubt:
If lexical scopes generate a new environment on each run and store their information, in an environment where code runs frequently, you need to declare var_of_scope = null at the end of the scope to free memory or JavaScript recognizes this automatically if not are there elements that refer to the environment?
No, that is almost never necessary.
Javascript uses garbage collection. When no values in any scope reference a value stored in memory, it is removed during the next run of garbage collector.
In the situation you describe:
function foo() {
let data = "some data here"
// do stuff with data
data = null
}
Setting the null here is not helpful. It does remove all references the previous value of data, but since the scope will end when the function ends, all local variables will be discarded along with it anyway.
In fact, this would prevent you from using the const keyword, which is a very very good thing to use. All your variables should be const by default, and you should change them to let only if you really need to assign them after initialization.
This is better:
function foo() {
const data = "some data here"
// do stuff with data
}
In general, you just don't have to worry about this. It's not easy to leak memory in javascript like it is in a language like C. It's possible but as long your following most best practices you'll probably be fine.
(Sorry for my poor English)
I finally realized why it's better to use let or const instead of var because var can't work with window properties!
However, is it a good idea still to use window properties as variable names just because you can bypass the problem by using other two keywords of creating variables?
For example:
var name = 'James';
console.log(name);
The above won't work because I'm using var keyword however if I used let or const, this wouldn't cause any error!
So once again, just because I can should I ?
Using variable names that exist as properties on the window object was never the real problem. Using them for global variables was (and still is). But if you are in a local scope, e.g. inside a function, you can name your local variables however you like.
If you cannot avoid global variables, you should strife to use as few as possible, and yes you should try to avoid collisions with other globals, be they properties of window or not. Using let or const just ensures that if they are window properties, your custom variable will shadow them, but you will still break other code that relies on these to be accessible as global variables with the builtin value. However, most of the time you cannot avoid global variables you also cannot avoid var, as let and const cannot be redeclared.
var
Function-scoped variable. It is visible in the current function. If it's outside all functions, then it's visible globally, assuming it's not in module scope.
let
Block-scoped variable. It's visible in the {} block where it was defined.
const
Block-scoped constant. Like let, it's block-scoped, but this one is constant.
object property
window is an object, so let's think about objects in general.
window.foo = "bar"; console.log(window.foo);
"Better"
One is not "better" than the other by definition. You will need to think about your needs and the conventions your team has agreed upon and apply them. Setting window attributes should not be a custom in general, because you are making it global, but sometimes you need to set window properties. Again: always think about what you need to achieve.
var variableOne;
var variableTwo;
var variableThree;
function veryInterestingFunction() {
var variableFour;
if(a){
variableFour = 'Good';
}
else {
variableFour = 'Decent';
}
console.log(variableFour);
}
$(window).on('scroll', function(){
veryInterestingFunction();
});
Here I have some variables in the global scope, a function declaring a variable and assigning a value to it, and calling this function on scroll.
This way on every scroll you are going to declare the "variableFour" which is not a good practice, right?
However I don't want to crowd the global scope with unnecessary variables and also can't use an IIFE. Is there a "best practice" way to declare the variable outside the function and still only possible to use it inside the scope of that function ?
http://jsfiddle.net/2jyddwwx/1/
to declare the variable outside the function and still only possible to use it inside the scope of that function ?
I guess, that's impossible
When I don't want to crowd the global scope, I will declare one global object, for example App = {}, and instead of global variables, I use it's properties.
App.variableOne;
App.variableTwo;
App.variableThree;
Or you can use classes in ES6
I don't think there's anything wrong with your code sample, I seriously doubt variable declaration is ever going to slow down your code. I'd definitely only start to worry about this kind of thing when you're absolutely certain it's causing issues (it won't), otherwise it might be wasted effort.
If you really want to optimize this, one thing you might be able to do is debouncing the veryInterestingFunction calls - that is if you don't necessarily need to respond to every single scroll event (depends on your logic).
As per your question, IIFE/function closure is essentially the only way to limit scope in JavaScript that I know of, so if you can't use that, I don't see any other option.
There is no problem in declaring an empty variable into your scope. If it is not global, it belongs to the scope.
And there is no need to fear for performance. If you declare variables within your scope, the Javascript garbage collector will empty that for you. Take a read at this article
I have a JS function which gets called on the page every few seconds. It's an AJAX update thing.
Being a function, I declare local variables. I don't want to use closures or global variables for various reasons.
I'd never considered this, but do I need to release/clear the variables at the end of the function to release memory or will JS do this for me automatically?
Generally, no. Variables declared with var are local and are garbage collected when you return. If you omit the var then the variables are global, and using the delete keyword may be useful for global variables in some instances, but generally it's good practice to declare all variables with var anyway to not pollute the window namespace.
delete can be useful when using prototype-based inheritence though, e.g:
function myclass() {
this.variable = 'myvalue'
...
delete this.variable // finished with this variable
}
var inst = new myclass()
Bear in mind that if inst is deleted or becomes out of scope (garbage collected) all the attributes in it will be deleted as well. delete can also be useful for deleting items from hash tables:
var d = {}
d['blah'] = 'myvalue'
...
delete d['blah']
There are some browser-specific garbage collection bugs. IE sometimes has problems cleaning attributes in DOM elements and closures etc for example, though many of these problems have been reduced in IE8 I believe.
Javascript has automatic garbage collection. You don't need to deallocate anything.
Variables are released once they are out of scope, in your case, the local variables that are declared inside your function will be automatically freed by js garbage collector, you don't have to worry about them.
Does JavaScript support garbage collection?
For example, if I use:
function sayHello (name){
var myName = name;
alert(myName);
}
do I need to use "delete" to delete the myName variable or I just ignore it?
no.
delete is used to remove properties from objects, not for memory management.
JavaScript supports garbage collection. In this case, since you explicitly declare the variable within the function, it will (1) go out of scope when the function exits and be collected sometime after that, and (2) cannot be the target of delete (per reference linked below).
Where delete may be useful is if you declare variables implicitly, which puts them in global scope:
function foo()
{
x = "foo"; /* x is in global scope */
delete x;
}
However, it's a bad practice to define variables implicitly, so always use var and you won't have to care about delete.
For more information, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
Ignore it - after the sayHello function completes, myName falls out-of-scope and gets gc'ed.
You don't need to do anything Ted, no need to delete this variable.
Refer: http://www.codingforums.com/archive/index.php/t-157637.html
As others mentioned, when the function exits then your variable falls out of scope, as it's scope is just within the function, so the gc can then clean it up.
But, it is possible for that variable to be referenced by something outside the function, then it won't be gc'ed for a while, if ever, as it is still has a reference to it.
You may want to read up on scoping in javascript:
http://www.webdotdev.com/nvd/content/view/1340/
With closures you can create memory leaks, which may be the problem you are trying to deal with, and is related to the problem I had mentioned:
http://www.jibbering.com/faq/faq_notes/closures.html