Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is const throwing an error on multiple runs of the code when inside an if() or try{}catch(e){}?
    text
    copied!<p>I'm trying to declare a bunch of constants using <code>const</code>. My problem is that testing the code in the Firebug console throws an error complaining about the 'redeclaration of const foo'.</p> <p>I've attempted wrapping it in a <code>try{}catch(e){}</code> block but that didn't help, and even when trying to get around it using the following code (posted minus all the console.info() "debugging" calls for clarity) it still throws the error when run for the second time:</p> <pre><code>if(!chk_constsDeclaredYet) { var chk_constsDeclaredYet = true; const foo="bar"; } </code></pre> <p>My question is that while the const is within the if(){}, when the code is 'run' for the second time, why is const foo being even being looked at?</p> <p><strong>NB: the code is to be run inside the firebug javascript console</strong> and the workflow i'm trying to achieve is:</p> <ol> <li>paste code into firebug console </li> <li>hit run (creating constants) </li> <li>i make an edit to the code in the console without reloading the page (the constants are still defined in the page context) </li> <li>hit run again (using the if(){} to avoid redeclaring the constants if they've already been declared by the previous run) </li> <li>repeat from (3)</li> </ol> <p><strong>firebug output:</strong></p> <pre><code>//FIRST RUN:: &gt;&gt;&gt; console.group() console.info('--code start--'); ...console.info('--code end--'); console.groupEnd() --code start-- chk_constsDeclaredYet = undefined foo = undefined --if()-- --if() running..-- --end if()-- chk_constsDeclaredYet = true foo = bar --code end-- //SECOND RUN:: &gt;&gt;&gt; console.group() console.info('--code start--'); ...console.info('--code end--'); console.groupEnd() TypeError: redeclaration of const foo { message="redeclaration of const foo", more...} </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload