Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is 'use strict' a must to use? [duplicate]

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?

like image 669
Mark Rogers Avatar asked Aug 26 '09 16:08

Mark Rogers


7 Answers

Update for ES6 modules

Inside native ECMAScript modules (with import and export statements) and ES6 classes, strict mode is always enabled and cannot be disabled.

Original answer

This article about Javascript Strict Mode might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More

To quote some interesting parts:

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

And:

Strict mode helps out in a couple ways:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

Also note you can apply "strict mode" to the whole file... Or you can use it only for a specific function (still quoting from John Resig's article):

// Non-strict code...

(function(){
  "use strict";

  // Define your library strictly...
})();

// Non-strict code...

Which might be helpful if you have to mix old and new code ;-)

So, I suppose it's a bit like the "use strict" you can use in Perl (hence the name?): it helps you make fewer errors, by detecting more things that could lead to breakages.

Strict mode is now supported by all major browsers.

like image 63
Pascal MARTIN Avatar answered Sep 28 '22 12:09

Pascal MARTIN


It's a new feature of ECMAScript 5. John Resig wrote up a nice summary of it.

It's just a string you put in your JavaScript files (either at the top of your file or inside of a function) that looks like this:

"use strict";

Putting it in your code now shouldn't cause any problems with current browsers as it's just a string. It may cause problems with your code in the future if your code violates the pragma. For instance, if you currently have foo = "bar" without defining foo first, your code will start failing...which is a good thing in my opinion.

like image 34
seth Avatar answered Sep 28 '22 11:09

seth


The statement "use strict"; instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript.

List of features (non-exhaustive)

  1. Disallows global variables. (Catches missing var declarations and typos in variable names)

  2. Silent failing assignments will throw error in strict mode (assigning NaN = 5;)

  3. Attempts to delete undeletable properties will throw (delete Object.prototype)

  4. Requires all property names in an object literal to be unique (var x = {x1: "1", x1: "2"})

  5. Function parameter names must be unique (function sum (x, x) {...})

  6. Forbids octal syntax (var x = 023; some devs assume wrongly that a preceding zero does nothing to change the number.)

  7. Forbids the with keyword

  8. eval in strict mode does not introduce new variables

  9. Forbids deleting plain names (delete x;)

  10. Forbids binding or assignment of the names eval and arguments in any form

  11. Strict mode does not alias properties of the arguments object with the formal parameters. (e.g. in function sum (a,b) { return arguments[0] + b;} This works because arguments[0] is bound to a and so on. ) (See examples section below to understand the difference)

  12. arguments.callee is not supported

[Ref: Strict mode, Mozilla Developer Network]


Examples:

  1. Strict mode code doesn't alias properties of arguments objects created within it
function show( msg ){
    msg = 42;
    console.log( msg );          // msg === 42
    console.log( arguments[0] ); // arguments === 42
}
show( "Hey" );

// In strict mode arguments[i] does not track the value of 
// the corresponding named argument, nor does a named argument track the value in the corresponding arguments[i]
function showStrict( msg ){
    "use strict";
    msg = 42;
    console.log( msg );          // msg === 42
    console.log( arguments[0] ); // arguments === "Hey"
}
showStrict( "Hey" );
like image 26
gprasant Avatar answered Sep 28 '22 13:09

gprasant


If people are worried about using use strict it might be worth checking out this article:

ECMAScript 5 'Strict mode' support in browsers. What does this mean?
NovoGeek.com - Krishna's weblog

It talks about browser support, but more importantly how to deal with it safely:

function isStrictMode(){
    return !this;
} 
/*
   returns false, since 'this' refers to global object and 
   '!this' becomes false
*/

function isStrictMode(){   
    "use strict";
    return !this;
} 
/* 
   returns true, since in strict mode the keyword 'this'
   does not refer to global object, unlike traditional JS. 
   So here, 'this' is 'undefined' and '!this' becomes true.
*/
like image 22
Jamie Hutber Avatar answered Sep 28 '22 11:09

Jamie Hutber


A word of caution, all you hard-charging programmers: applying "use strict" to existing code can be hazardous! This thing is not some feel-good, happy-face sticker that you can slap on the code to make it 'better'. With the "use strict" pragma, the browser will suddenly THROW exceptions in random places that it never threw before just because at that spot you are doing something that default/loose JavaScript happily allows but strict JavaScript abhors! You may have strictness violations hiding in seldom used calls in your code that will only throw an exception when they do eventually get run - say, in the production environment that your paying customers use!

If you are going to take the plunge, it is a good idea to apply "use strict" alongside comprehensive unit tests and a strictly configured JSHint build task that will give you some confidence that there is no dark corner of your module that will blow up horribly just because you've turned on Strict Mode. Or, hey, here's another option: just don't add "use strict" to any of your legacy code, it's probably safer that way, honestly. DEFINITELY DO NOT add "use strict" to any modules you do not own or maintain, like third party modules.

I think even though it is a deadly caged animal, "use strict" can be good stuff, but you have to do it right. The best time to go strict is when your project is greenfield and you are starting from scratch. Configure JSHint/JSLint with all the warnings and options cranked up as tight as your team can stomach, get a good build/test/assert system du jour rigged like Grunt+Karma+Chai, and only THEN start marking all your new modules as "use strict". Be prepared to cure lots of niggly errors and warnings. Make sure everyone understands the gravity by configuring the build to FAIL if JSHint/JSLint produces any violations.

My project was not a greenfield project when I adopted "use strict". As a result, my IDE is full of red marks because I don't have "use strict" on half my modules, and JSHint complains about that. It's a reminder to me about what refactoring I should do in the future. My goal is to be red mark free due to all of my missing "use strict" statements, but that is years away now.

like image 35
DWoldrich Avatar answered Sep 28 '22 11:09

DWoldrich


Using 'use strict'; does not suddenly make your code better.

The JavaScript strict mode is a feature in ECMAScript 5. You can enable the strict mode by declaring this in the top of your script/function.

'use strict';

When a JavaScript engine sees this directive, it will start to interpret the code in a special mode. In this mode, errors are thrown up when certain coding practices that could end up being potential bugs are detected (which is the reasoning behind the strict mode).

Consider this example:

var a = 365;
var b = 030;

In their obsession to line up the numeric literals, the developer has inadvertently initialized variable b with an octal literal. Non-strict mode will interpret this as a numeric literal with value 24 (in base 10). However, strict mode will throw an error.

For a non-exhaustive list of specialties in strict mode, see this answer.


Where should I use 'use strict';?

  • In my new JavaScript application: Absolutely! Strict mode can be used as a whistleblower when you are doing something stupid with your code.

  • In my existing JavaScript code: Probably not! If your existing JavaScript code has statements that are prohibited in strict-mode, the application will simply break. If you want strict mode, you should be prepared to debug and correct your existing code. This is why using 'use strict'; does not suddenly make your code better.


How do I use strict mode?

  1. Insert a 'use strict'; statement on top of your script:

     // File: myscript.js
    
     'use strict';
     var a = 2;
     ....
    

    Note that everything in the file myscript.js will be interpreted in strict mode.

  2. Or, insert a 'use strict'; statement on top of your function body:

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

    Everything in the lexical scope of function doSomething will be interpreted in strict mode. The word lexical scope is important here. For example, if your strict code calls a function of a library that is not strict, only your code is executed in strict mode, and not the called function. See this answer for a better explanation.


What things are prohibited in strict mode?

I found a nice article describing several things that are prohibited in strict mode (note that this is not an exhaustive list):

Scope

Historically, JavaScript has been confused about how functions are scoped. Sometimes they seem to be statically scoped, but some features make them behave like they are dynamically scoped. This is confusing, making programs difficult to read and understand. Misunderstanding causes bugs. It also is a problem for performance. Static scoping would permit variable binding to happen at compile time, but the requirement for dynamic scope means the binding must be deferred to runtime, which comes with a significant performance penalty.

Strict mode requires that all variable binding be done statically. That means that the features that previously required dynamic binding must be eliminated or modified. Specifically, the with statement is eliminated, and the eval function’s ability to tamper with the environment of its caller is severely restricted.

One of the benefits of strict code is that tools like YUI Compressor can do a better job when processing it.

Implied Global Variables

JavaScript has implied global variables. If you do not explicitly declare a variable, a global variable is implicitly declared for you. This makes programming easier for beginners because they can neglect some of their basic housekeeping chores. But it makes the management of larger programs much more difficult and it significantly degrades reliability. So in strict mode, implied global variables are no longer created. You should explicitly declare all of your variables.

Global Leakage

There are a number of situations that could cause this to be bound to the global object. For example, if you forget to provide the new prefix when calling a constructor function, the constructor's this will be bound unexpectedly to the global object, so instead of initializing a new object, it will instead be silently tampering with global variables. In these situations, strict mode will instead bind this to undefined, which will cause the constructor to throw an exception instead, allowing the error to be detected much sooner.

Noisy Failure

JavaScript has always had read-only properties, but you could not create them yourself until ES5’s Object.createProperty function exposed that capability. If you attempted to assign a value to a read-only property, it would fail silently. The assignment would not change the property’s value, but your program would proceed as though it had. This is an integrity hazard that can cause programs to go into an inconsistent state. In strict mode, attempting to change a read-only property will throw an exception.

Octal

The octal (or base 8) representation of numbers was extremely useful when doing machine-level programming on machines whose word sizes were a multiple of 3. You needed octal when working with the CDC 6600 mainframe, which had a word size of 60 bits. If you could read octal, you could look at a word as 20 digits. Two digits represented the op code, and one digit identified one of 8 registers. During the slow transition from machine codes to high level languages, it was thought to be useful to provide octal forms in programming languages.

In C, an extremely unfortunate representation of octalness was selected: Leading zero. So in C, 0100 means 64, not 100, and 08 is an error, not 8. Even more unfortunately, this anachronism has been copied into nearly all modern languages, including JavaScript, where it is only used to create errors. It has no other purpose. So in strict mode, octal forms are no longer allowed.

Et cetera

The arguments pseudo array becomes a little bit more array-like in ES5. In strict mode, it loses its callee and caller properties. This makes it possible to pass your arguments to untrusted code without giving up a lot of confidential context. Also, the arguments property of functions is eliminated.

In strict mode, duplicate keys in a function literal will produce a syntax error. A function can’t have two parameters with the same name. A function can’t have a variable with the same name as one of its parameters. A function can’t delete its own variables. An attempt to delete a non-configurable property now throws an exception. Primitive values are not implicitly wrapped.


Reserved words for future JavaScript versions

ECMAScript 5 adds a list of reserved words. If you use them as variables or arguments, strict mode will throw an error. The reserved words are:

implements, interface, let, package, private, protected, public, static, and yield


Further Reading

  • Strict Mode - JavaScript | MDN
  • Browser support for strict mode
  • Transitioning to strict mode
like image 21
sampathsris Avatar answered Sep 28 '22 12:09

sampathsris


I strongly recommend every developer to start using strict mode now. There are enough browsers supporting it that strict mode will legitimately help save us from errors we didn’t even know were in your code.

Apparently, at the initial stage there will be errors we have never encountered before. To get the full benefit, we need to do proper testing after switching to strict mode to make sure we have caught everything. Definitely we don’t just throw use strict in our code and assume there are no errors. So the churn is that it’s time to start using this incredibly useful language feature to write better code.

For example,

var person = {
    name : 'xyz',
    position : 'abc',
    fullname : function () {  "use strict"; return this.name; }
};

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.

like image 43
Pank Avatar answered Sep 28 '22 13:09

Pank