Strict mode

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");
//!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) { = name;

var ferdinand = Person("Ferdinand"); //oops

In strict mode, the result is different.

function Person(name) { = name;

var ferdinand = Person("Ferdinand");
//!TypeError:Cannot set property ''name'' of undefined
Points to remember
  1. The "use strict" directive is recognized only at the beginning of a script or a function.
  2. It disallows giving a function multiple parameters with the same name.
  3. Using a variable or object, without declaring it, is not allowed.
  4. Deleting a variable or object or functionis not allowed.
  5. Octal numeric literals, Octal escape characters are not allowed.
  6. Writing to a read-only or get-only property is not allowed.
  7. Deleting an undeletable property is not allowed:
  8. The word eval, arguments cannot be used as a variable.
  9. The with statement is not allowed:
  10. eval() is not allowed to create variables in the scope from which it was called.

Related Tutorial
Follow Us #
Contents +