Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to reset Chrome DevTools console's context

Is there any feature in Chrome > DevTools > console which clears / resets / removes variables and functions declared while testing through it (just like calling clear, clears the logs)?

Let's say, for an example, I have a variable declared with let keyoword..

let str = "Hello";

..and I run it through console once and I re run the same code through console again.

Yeah, It would throw an error "Identifier 'str' has already been declared" as expected because the variable has already been declared and it can't be declared again (unlike declaring it with var keyword) so to re run the code through console, I have to refresh the page which resets the context of the frame / target.

Is there any other option?

like image 624
jeetaz Avatar asked Jul 05 '18 12:07

jeetaz


People also ask

How do I clear all variables in console?

" clear() : Clears the console output area." Just hit F5 to refresh the page. And don't use a global name variable.


1 Answers

As it was already mentioned in comments, the code is evaluated in global scope, so there is no way to undeclare a variable that was declared with let, etc. as a global except by reloading current window.

Evaluating

let str = "Hello";

in succession will always trigger Identifier 'str' has already been declared error.

One workaround is to evaluate code as complete block-scoped snippets:

{
  let str = "Hello";
  console.log(str);
}

Notice that blocks don't have return value (they are statements and not expressions), but the last expression in a block is handled by console, so console.log can be omitted.

{ let str = "Hello"; str }

will output Hello in console.

Alternatively, IIFE can be used to return a value :

(() => {
  let str = "Hello";
  return str;
})()

As a rule of thumb, try to avoid block-scoped declarations in console to avoid this problem. This snippet can be evaluated without problems in succession:

  var str = "Hello"; // instead of `let str = "Hello"`
  var Foo = class Foo {} // instead of `class Foo {}`
like image 97
Estus Flask Avatar answered Sep 17 '22 15:09

Estus Flask