Home

JavaScript Strict Mode

|
Updated:  
2016-03-26 07:58:56
|
JavaScript Essentials For Dummies
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 author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.