What does "use strict" do in JavaScript, and what is the reasoning behind it?

Viewed 1184527

Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error:

Problem at line 1 character 1: Missing "use strict" statement.

Doing some searching, I realized that some people add "use strict"; into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.

So what is "use strict"; all about, what does it imply, and is it still relevant?

Do any of the current browsers respond to the "use strict"; string or is it for future use?

31 Answers

If you use a browser released in the last year or so then it most likely supports JavaScript Strict mode. Only older browsers around before ECMAScript 5 became the current standard don't support it.

The quotes around the command make sure that the code will still work in older browsers as well (although the things that generate a syntax error in strict mode will generally just cause the script to malfunction in some hard to detect way in those older browsers).

Use Strict is used to show common and repeated errors so that it is handled differently , and changes the way java script runs , such changes are :

  • Prevents accidental globals

  • No duplicates

  • Eliminates with

  • Eliminates this coercion

  • Safer eval()

  • Errors for immutables

you can also read this article for the details

"use strict"; Defines that JavaScript code should be executed in "strict mode".

  • The "use strict" directive was new in ECMAScript version 5.
  • It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.
  • The purpose of "use strict" is to indicate that the code should be executed in "strict mode".
  • With strict mode, you can not, for example, use undeclared variables.

All modern browsers support "use strict" except Internet Explorer 9 and lower.

Disadvantage

If a developer used a library that was in strict mode, but the developer was used to working in normal mode, they might call some actions on the library that wouldn’t work as expected.

Worse, since the developer is in normal mode, they don’t have the advantages of extra errors being thrown, so the error might fail silently.

Also, as listed above, strict mode stops you from doing certain things.

People generally think that you shouldn’t use those things in the first place, but some developers don’t like the constraint and want to use all the features of the language.

Strict mode can prevent memory leaks.

Please check the function below written in non-strict mode:

function getname(){
    name = "Stack Overflow"; // Not using var keyword
    return name;
}
getname();
console.log(name); // Stack Overflow

In this function, we are using a variable called name inside the function. Internally, the compiler will first check if there is any variable declared with that particular name in that particular function scope. Since the compiler understood that there is no such variable, it will check in the outer scope. In our case, it is the global scope. Again, the compiler understood that there is also no variable declared in the global space with that name, so it creates such a variable for us in the global space. Conceptually, this variable will be created in the global scope and will be available in the entire application.

Another scenario is that, say, the variable is declared in a child function. In that case, the compiler checks the validity of that variable in the outer scope, i.e., the parent function. Only then it will check in the global space and create a variable for us there. That means additional checks need to be done. This will affect the performance of the application.


Now let's write the same function in strict mode.

"use strict"
function getname(){
    name = "Stack Overflow"; // Not using var keyword
    return name;
}
getname();
console.log(name); 

We will get the following error.

Uncaught ReferenceError: name is not defined
at getname (<anonymous>:3:15)
at <anonymous>:6:5

Here, the compiler throws the reference error. In strict mode, the compiler does not allow us to use the variable without declaring it. So memory leaks can be prevented. In addition, we can write more optimized code.

Strict mode eliminates errors that would be ignored in non-strict mode, thus making javascript “more secured”.

Is it considered among best practices?

Yes, It's considered part of the best practices while working with javascript to include Strict mode. This is done by adding the below line of code in your JS file.

'use strict';

in your code.

What does it mean to user agents?

Indicating that code should be interpreted in strict mode specifies to user agents like browsers that they should treat code literally as written, and throw an error if the code doesn't make sense.

For example: Consider in your .js file you have the following code:

Scenario 1: [NO STRICT MODE]

var city = "Chicago"
console.log(city) // Prints the city name, i.e. Chicago

Scenario 2: [NO STRICT MODE]

city = "Chicago"
console.log(city) // Prints the city name, i.e. Chicago

So why does the variable name is being printed in both cases?

Without strict mode turned on, user agents often go through a series of modifications to problematic code in an attempt to get it to make sense. On the surface, this can seem like a fine thing, and indeed, working outside of strict mode makes it possible for people to get their feet wet with JavaScript code without having all the details quite nailed down. However, as a developer, I don't want to leave a bug in my code, because I know it could come back and bite me later on, and I also just want to write good code. And that's where strict mode helps out.

Scenario 3: [STRICT MODE]

'use strict';

city = "Chicago"
console.log(city) // Reference Error: asignment is undeclared variable city.

Additional tip: To maintain code quality using strict mode, you don't need to write this over and again especially if you have multiple .js file. You can enforce this rule globally in eslint rules as follows:

Filename: .eslintrc.js

module.exports = {
    env: {
        es6: true
    },
    rules : {
        strict: ['error', 'global'],
        },
    };
    

Okay, so what is prevented in strict mode?

  • Using a variable without declaring it will throw an error in strict mode. This is to prevent unintentionally creating global variables throughout your application. The example with printing Chicago covers this in particular.

  • Deleting a variable or a function or an argument is a no-no in strict mode.

    "use strict";
     function x(p1, p2) {}; 
     delete x; // This will cause an error
    
  • Duplicating a parameter name is not allowed in strict mode.

     "use strict";
     function x(p1, p1) {};   // This will cause an error
    
  • Reserved words in the Javascript language are not allowed in strict mode. The words are implements interface, let, packages, private, protected, public. static, and yield

For a more comprehensive list check out the MDN documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

JavaScript was designed and implemented hastily because of the browser wars and bad management. As a result many poor design decisions, un-intuitive syntax and confusing semantics found their way into the language. Strict mode aims to amend some of these mistakes.

But fixing these mistakes without creating alternative interpretation breaks backward compatibility. So, "use strict" directive creates that alternative interpretation of the code while communicating it to the programmer.

For example, this keywords refers to the object in a method definition, like this or self in other languages.

let o = {
  name: 'John Doe',
  sayName: function(){
    console.log(this.name);
  }
};

o.sayName(); // 'John Doe'

this has no purpose outside the method context but all JavaScript functions have this keyword whether they are methods or not:

function run() {
  console.log(this);
}

run(); // Window

Here this resolves to the global object which does not make sense and serves no purpose because global object is already available in the scope.

In strict mode this in a global function resolves to undefined, which is what we expect.

"use strict"

function run() {
  console.log(this);
}

run(); // undefined

Some mistakes can not be fixed even in strict mode because syntax should be valid for older browsers since they ignore "strict mode" directive. This is by design.

strict mode enables strict features in the v8 engine. Short example of some features:

You can enable it globally by writing:

'use strict'; // strict mode enabled!

Per function you just include in function:

let myfunc = () => {
  'use strict'; // strict mode enabled
  
   b = 0; // broke
}
  • You MUST declare a variable before using it (sane imo):
  var x;
  x = '0'; // ok
  y = '';  // not ok
  • es6 features are enabled (this is browser dependent), for node v4+ this is important.

  • Performance, in some cases, is better.

There are more features as well, check here for more!

The "use strict" Directive

It is not a statement, but a literal expression, ignored by earlier versions of JavaScript. The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables.

//It's a new feature of ECMAScript 5. 
//With strict mode, you can not, for example, use undeclared variables.

Insert a 'use strict'; statement on top of your script:
/***START ANY JS FILE***/
'use strict';
var a = 2;
....
/***END***/ 
Or, insert a 'use strict'; statement on top of your function body:

function doSomething() {
'use strict';
...
}   

For Example:

class Person {
constructor() {
 a = 0;
 this.name = a;
 }
}

let p = new Person(); // ReferenceError: Can't find variable: a
Related