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 (localStorage.clear()
) any variables I've assigned still show up.
For example, if I do something like var name = "Bob";
I clear and close the console, reopen it, and look for the value of name
, it's still Bob
.
What's the best way to clear these out?
Use the short cut Ctrl + L to clear the console. Use the clear log button on the top left corner of the chrome dev tools console to clear the console. On MacOS you can use Command + K button.
clear() The console. clear() method clears the console if the console allows it. A graphical console, like those running on browsers, will allow it; a console displaying on the terminal, like the one running on Node, will not support it, and will have no effect (and no error).
To view any variable in chrome, go to "Sources", and then "Watch" and add it. If you add the "window" variable here then you can expand it and explore.
Whenever you are working chrome, try this: Press F12 and open the developer tools. On the refresh button, on the top left of the browser window, do a right click.
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
Easiest way to clear data from the console is to refresh the page.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With