Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome console clear assignment and variables

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";

enter image description here

I clear and close the console, reopen it, and look for the value of name, it's still Bob.

enter image description here

What's the best way to clear these out?

like image 978
spex5 Avatar asked Dec 14 '15 15:12

spex5


People also ask

How do I clear a variable in chrome console?

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.

What is console Clear ()?

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).

How do I view all variables in chrome?

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.

How do I refresh the chrome console?

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.


2 Answers

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

like image 84
pjivers Avatar answered Oct 18 '22 19:10

pjivers


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.

like image 46
sdgluck Avatar answered Oct 18 '22 19:10

sdgluck