Anki desktop (and maybe AnkiMobile) only updates part of the page when flipping cards, so redeclaring a variable already declared with const or let in the global namespace (i.e. at the top level of the script) will cause an error.
You can try either of the following:
Replace let and const in the first two lines with var
Wrap the whole code in curly braces (or in IIFE) to prevent polluting the global namespace
I’m using quite a bit of (plain) Javascript and it works pretty well for me. Note that you can use hacks like delaying code execution with
setTimeout(function() {
//your code to be executed after delayInMilliseconds
}, delayInMilliseconds);
(if you don’t want to show the changes being applied, you can set display to none first and then set it to block afterwards; that way you only get a small delay when showing the card, which is quite tolerable)
For example, in a test deck I wanted to randomly rotate an image (and had to do the same rotation for the back side) and that delayed code execution was the thing that saved the day.
Talking about using Javascript, the anki-persistence code by Simon Lammers is suuuper useful.
I was asking this question because I was having quite a bit of trouble with inserting variables inside backticks into strings inside my script. Then I also had to include a promise event listener because my script was working only on the first card of the deck.
Hm, I don’t have much experience with backticks, but what I can get from a 5s Google search is that they’re a somewhat special feature (for literals?). My advice is to prepare the data outside of Anki and only use basic JavaScript commands in Anki. Then it should work fine. (At least that’s my experience so far…)