Bug: JavaScript won't run properly on 2.1.49

I use JavaScript in the cards’ edit window to hint answers, to shuffle multiple choices, and for other reasons. I run Anki on Linux desktop.

Everything worked as intended up until I installed the latest version (2.1.49). Since then JavaScript runs well only once in each deck review and then it doesn’t run at all for some note types. For other note types it runs well only for the first card and not whatsoever for the other card. I tried to troubleshoot it but I had no luck. It behaves so on reviews, on previews, and on card editing.

Here is a card example I have problems with. The JS only runs successfully only once as I described.

<div class="cards">
	<span class="clarification">number of letters:</span> <span id="word-length"></span>
	<span class="clarification">letters in word:</span> <span id="random-letters"></span>
<dir class="tags">

	const word = "{{Back}}";
	const wordLength = document.getElementById("word-length");
	wordLength.innerHTML = word.length;
	const randomLetters = document.getElementById("random-letters");
  var wordLetters = word;
	for (var i = 0; i < (word.length)/3; i++){
		const index = Math.floor(Math.random()*wordLetters.length);
		if (i+1 < (word.length)/3)
			randomLetters.innerHTML += wordLetters[index]+", ";
			randomLetters.innerHTML += wordLetters[index];
		wordLetters = wordLetters.slice(0, index)+wordLetters.slice(index+1)

Thank you.

You could use this addon to debug your cards.
One thing I noticed: You should use var instead of const.


Thanks for the reply! I solved the problem with a similar solution to yours.

I changed them but nothing ran again. Then I looked at the code that run without issues to see if I have any const declarations there; it had but not in the main block. Then I figured to make the main block not main by putting {} around the code and everything run like it used to run before.

I didn’t use the addon to see the debug messages but I infer that in the latest version the namespace for each card is common for all in the session and not refreshed on each card. So every time I declare a variable is like redeclaring it so JS throws error. Putting the code in {} makes the code in each card a separate namespace so there is no issues with redeclaring variables.

Now that I have found my solution, I think that this bug is more like a feature because I can have variables that maintain their value throughout the session, and make it more programmable.