Search code examples
javascriptjquerystrictuse-strict

Why doesn't "use strict" (JavaScript) detect an undeclared variable?


I'm trying to get the "use strict"; directive to work, and having a bit of trouble. In the following file FireFox 9 will (correctly) detect that someVar hasn't been declared on line 3, but fails to detect that theVar hasn't been declared on line 19. I'm stumped as to why this would be the case.

"use strict"; // this will cause the browser to check for errors more aggresively

someVar = 10; // this DOES get caught // LINE 3

// debugger; // this will cause FireBug to open at the bottom of the page/window
        // it will also cause the debugger to stop at this line

    // Yep, using jQuery & anonymous functions
$(document).ready( function(){  
    alert("document is done loading, but not (necessarily) the images!");  

    $("#btnToClick").click( function () {

        alert("About to stop");
        var aVariable = 1;
        debugger; // stop here!
        alert("post stop " + aVariable );

        // this lacks a "var" declaration:
        theVar = 10; // LINE 19  // this is NOT getting caught

        // needs a closing "
        // alert("hi);
        console.log("Program is printing information to help the developer debug a problem!");  
    });

});

Solution

  • You need to invoke the handler before the error is thrown. In other words, click the #btnToClick.

    Example fiddle: http://jsfiddle.net/X3TQb/