Using `const` in Snippets

2017-04-05

Chrome Developer Tools has a feature called “Snippets”. It let’s you store and execute snippets of JS in the context of the current window. This is a good alternative over pasting code directly into the console.

Let’s take the following code as an example:

snippet-with-problem.js
1
2
const foo = 'bar'
console.log(foo)

Click “Execute” (or press Ctrl+Enter) and bar is printed in the console.

Now, try to run it again and you’ll get an error:

1
2
Uncaught SyntaxError: Identifier 'foo' has already been declared
at <anonymous>:1:1

This is obvious in retrospect. JS does not allow reassigning (nor redeclaring) const variables.

The fix is surprisingly easy. Create a scope for your variables. Also, go ahead and set it to strict mode, because you should.

snippet-fixed.js
1
2
3
4
5
{
'use strict'
const foo = 'bar'
console.log(foo)
}

There you go. A Snippet you can execute as many times as you want.


Comments: