Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

Strict mode is an optional way to force web browsers to run a restricted version of JavaScript. Strict mode treats mistakes in your code that are normally considered bad style as actual errors that will cause your programs to not run. Using strict mode makes your JavaScript code more secure and can even make your programs run faster.

Strict mode is a new feature of JavaScript, but it's supported by every modern web browser, and by versions 10 and higher of Internet Explorer.

To enable strict mode, put the following statement in your JavaScript code before anything else:

"use strict";

If you want to enable strict mode just for a function, you can just put the "use strict" statement as the first statement within the function body. For example:

function myFunction() {
 "use strict";
 // rest of the function here
}

Some of the differences between strict mode and the normal mode for running JavaScript are that strict mode

  • Makes it impossible to accidentally create a global variable, as in the following statement:

    myVariable = "hello World!"; 
    /* normally, if myVariable doesn't already exist,  
    this statement would create a global variable 
    called myVariable. In strict mode, it 
    would cause an error. */
  • Causes assignments that would normally just fail silently to throw errors. For example:

    NaN = "a number!"; 
    /* normally, trying to assign a value to a 
    non-writable variable will just fail. In 
    strict mode, it would cause an error. */
  • Causes attempts to delete undeletable properties will cause an error. For example:

    delete Object.prototype
    // throws an error in strict mode
  • Requires that properties of an object are unique

  • Requires that parameter names are unique

  • Creates additional reserved keywords so that the code you write today in strict mode won't conflict with keywords in future versions of JavaScript.

Check here to find out more about what's different between strict mode and normal JavaScript execution.

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: