I am learning JavaScript and have been doing a lot of testing in the Chrome console. Even if I clear the console, or use any of the commands I\'ve seen in other threads (
A simple solution to this problem is to wrap any code that you don't want in the global scope in an immediately-invoked function expression (IIFE). All the variables assigned in the function's scope are deallocated when the function ends:
(function() {
// Put your code here...
})();
For more info on IIFEs: https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
[Update]
In ES6 you can use blocks (so long as you use let
instead of var
):
{
// Put your code here...
}
For more info on blocks: http://exploringjs.com/es6/ch_core-features.html#sec_from-iifes-to-blocks
If you right-click the refresh icon in chrome(chrome devtools need to be opened, F12/Right Click on the page -> Inspect
), after a second or two you will get the option to hard reload. Hard Reload will clear all stored variables.
Ctrl+Shift+R (Windows) / Cmd+Shift+R (Mac) will do the same without opening the devtools.
Console.clear()
Use this command in your browser console and see the magic, very handy to use and works perfectly as per best practices of using chrome console,
What you are affecting when declaring any variables or functions within the developer console is the global execution context, which for web browsers is window.
When you clear() the console you are telling Chrome to remove all visible history of these operations, not clear the objects that you have attached to window
.
To do this you must manually delete
each object by its reference:
delete name;
name //=> undefined
If the overhead of having to repeatedly remove multiple objects via delete
is too much, store each value as a property of an object, e.g. data
, that you can delete along with all properties in one statement:
var data = {};
data.name = 'Bob';
data.age = 60;
delete data;
data.name //=> ReferenceError: data is not defined
data.age //=> ReferenceError: data is not defined
Things have changed a lot on chrome dev tools. delete name
does not help;
//for example if you have declared a variable
`const x = 2;`
//Now sometime later you want to use the same variable
`const x = 5` you will get an error
//if you try to delete it you will get false
delete x;
But a reload of page while console is still open. will refresh the console context and now the x is not available and you can redefine it. Hope this helps someone testing or trying things on the console of chrome. i use it a lot.
Clearing the console doesn't clear out the variables from the memory rather it just clears the data from the user interface.
Reloading the page clears the console data. I hope that should be fine as you mentioned that you are just testing and learning javascript.
Hope that helps!