A way to reset Chrome DevTools console's context
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 {}`
Basically you have two options:
- The easy one: do
window.location.reload()
in the console. - You can use
Block scope
orIIFE
pattern.
What block scope
and IIFE
will do is the won't declare the variables in global scope like you were doing. Instead, it'll declare those variable within that scope. Also, unlike let
, var
lets you re-declare it.