Chrome console clear assignment and variables

折月煮酒 提交于 2019-11-28 04:53:10

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

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

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!

Just Reload for new context with clear history and old commands execution

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.

If you want to remove that variable then

delete name;
user2841183
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,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!