Now you might ask: “What is the issue with using block scoped variables at the top level of a <script>
tag, i.e. why is const
and let
working inside functions, but not outside?”
A variable with the same name must not be declared multiple times in the same scope using the let or const keywords.
Consider this script:
let num = 1
let num = 42
The second line will throw the following error:
Uncaught SyntaxError: Identifier 'num' has already been declared.
Say you used let/const at the top-level of a <script>
tag, which is the outermost scope. When Anki executes that script twice in the same context (i.e. when switching to a new card), it will throw that error.
This wasn’t an issue before Anki switched to persisting its webview during review. Before 2.1.41, the whole document was refreshed with each card, so you could use let/const/var interchangeably.
Now, you’ll need to use var
at the outermost scope.