You're seeing this behaviour because your code references a variable toggle
which is declared in the same statement. It works in the console because by the time the expression is evaluated for the second time toggle
now exists.
I can't suggest an improvement because I don't know how you expect the function to work, given you don't define an initial value for toggle
before your statement evaluates.
Also, you're using jQuery, but using Vanilla.js code-style within your jQuery event-handler. You should change your code to be more consistent: either only use idiomtic jQuery or idiomatic Vanilla.js.