Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!");  
    });

});
like image 957
MikeTheTall Avatar asked Dec 25 '11 16:12

MikeTheTall


2 Answers

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

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

like image 143
David Hellsing Avatar answered Oct 31 '22 16:10

David Hellsing


Javascript is kinda funny when it comes to variable scope. If you were to run different code before running this code, you could have the variables declared, and there wouldn't be any error, and for that reason it's hard to throw errors for missing variables except at runtime.

like image 1
Thomas Hunter II Avatar answered Oct 31 '22 16:10

Thomas Hunter II