By enabling strict mode, JavaScript can be made a more strict by putting the string "use strict
" at the top of a file or a function body.
In short, putting a "use strict
" at the top of your program will help you spot a problem.
Here's an example:
function canYouSpotTheProblem() { "use strict"; for (counter = 0; counter & lt; 10; counter++) console.log("Happy happy"); } canYouSpotTheProblem(); //!ReferenceError:counter is not defined
When you create a variable without using ''var
'' keyword JavaScript will not throw error. JavaScript creates a global variable and uses that. But in strict
mode, an error is reported instead.
It should be noted, though, that this doesn't work when the variable in question already exists as a global variable, but only when assigning to it would have created it.
In strict
mode the binding holds the value undefined in functions that are not called as methods. When making such a call outside of strict mode, this refers to the global scope object. So if you accidentally call a method or constructor incorrectly in strict mode, JavaScript will produce an error as soon as it tries to read something from this, rather than working with the global object, creating and reading global variables.
In the below example it calls a constructor without the new keyword, so that its this will not refer to a newly constructed object. So the call to Person succeeded but returned an undefined value and created the global variable name.
function Person(name) { this.name = name; } var ferdinand = Person("Ferdinand"); //oops console.log(name); //!Ferdinand
In strict mode, the result is different.
"usestrict"; function Person(name) { this.name = name; } //Oops,forgot''new'' var ferdinand = Person("Ferdinand"); //!TypeError:Cannot set property ''name'' of undefined