Technical Articles => Web =>  JavaScript

Strict mode in JavaScript

Source : Peter    Date : 2013-01-17 05:00:26  

1. Introduction

In addition to normal mode, ECMAScript 5 includes the other mode : strict mode. It means it will make JavaScript codes execute in a more strict environment.

The purposes to have strict mode are:

  1. Remove some unreasonable and parts of JavaScript syntax. Reduce some of the quirk behaviors.
  2. Remove some insecure parts of code execution. Make the execution environment more secure
  3. Improve interpret efficiency and increase the execution speed
  4. Build foundation for future JavaScript version

Strict mode shows that JavaScript is moving toward more reasonable and more secure. Most of the mainstream browsers including IE 10 now support this mode. Many large projects are now embracing this mode.

Same codes may have different results when executing in different modes. Some codes which can run in normal mode may not work on strict mode. So it's better to understand JavaScript in detail, this will make you a better programmer as well.

2. Enter strict mode

To use strict mode, you should have the following line in your codes:

"use strict";

Old browsers may treat it as a normal string and will ignore it.

3. How to use it

Strict mode can be invoked using two methods.

3.1. For the whole script file

If you put "use strict" at the first line of your script, then the whole script will execute in strict mode. If you don't put it at the first line, then it will have no effect, the whole script will execute in normal mode. If you merge different scripts into one single script, you should put special attention on this.

 <script>
    "use strict";
    console.log("This is strict mode");
  </script>

  <script>
    console.log("This is normal mode");
  </script>

The above codes have two script section, the first one will execute in strict mode and the second one will execute in normal mode.

3.2. For single function

If you put the "use strict" at the first line of your function body, then the function will execute in strict mode.

  function strict(){
    "use strict";
    return "This is strict mode";
  }

  function notStrict() {
    return "This is normal mode";
  }

3.3 Alternative way

Because the first method is not suitable for script merging, then we can use the second method to put the whole script into a function which executes immediately when loading.

(function (){

    "use strict";

    // some code here

   })();

4. Syntax and behavior change

In strict mode, there are some changes to the syntax and behavior.

4.1 Explicit global variable declaration

In normal mode, if a variable is assigned directly before it is declared, then it will be global by default. In strict mode, this is not allowed, all global variables have to be declared explicitly.

    "use strict";

  v = 1; // Error, v is not declared

  for(i = 0; i < 2; i++) { // Error, i is not declared
  }

In strict mode, all variables must be declared with var before they can be used.

4.2 Static binding

One feature of JavaScript is that it allows dynamic binding, i.e, some properties and methods are bond to an object is decided at runtime but not at compile time.

In strict mode, the dynamic binding behavior is restricted, in some situations, only static binding is allowed, i.e, properties and methods are bond to one object while compiling, this improves the compilation efficiency and increase code readability.

a. Disallow with statement

   "use strict";

  var v = 1;

  with (o){ // Syntax error
    v = 2;
  }

b. Create eval scope

In normal mode, there are two variable execution scopes : global scope and function scope. In strict mode, one more scope is added : eval scope.

In normal mode, the scope of eval depends on whether it runs in global scope or function scope. In strict mode, eval itself is an scope.

   "use strict";

  var x = 2;

  console.info(eval("var x = 5; x")); // 5

  console.info(x); // 2

4.3. The improved security capability

1. Disallow this to point to global object

  function f(){
    return !this;
  } 
  // Return false,Because "this" points to global object,"!this"  is false

  function f(){ 
    "use strict";
    return !this;
  } 
  // Return true,because in strict mode,this is undefined,so "!this" is true。

So when using constructors, if we don't use new, this will not point to global object but it will throw an error.

    function f(){

    "use strict";

    this.a = 1;

  };

  f();// Error, this is undefined.

2. Disallow calling stack

  function f1(){

    "use strict";

    f1.caller; // Error

    f1.arguments; // Error

  }

  f1();

4.4 Disallow deleting variables

In strict mode, we cannot delete variables, only those variables with configurable to be true can be deleted.

 "use strict";

  var x;

  delete x; // Syntax error

  var o = Object.create(null, 'x', {
      value: 1,
      configurable: true
  });

  delete o.x; // Deletion success

4.5 Explicit error report

In normal mode, if you assign value to a read only property of an object, it will fail silently. But in strict mode, it will through an error.

 "use strict";

  var o = {};

  Object.defineProperty(o, "v", { value: 1, writable: false });

  o.v = 2; // Error

In strict mode, it will throw error if assigning a value to a variable read using getter method.

  "use strict";

  var o = {

    get v() { return 1; }

  };

  o.v = 2; // Error

In strict mode, it will throw an error if adding new properties to an object which is prevented to extend.

  "use strict";

  var o = {};

  Object.preventExtensions(o);

  o.v = 1; // Error

In strict mode, it will throw an error if deleting an properties which can not be deleted.

  "use strict";

  delete Object.prototype; // Error

4.6 Rename error

1. Object cannot have two properties with the same name

  "use strict";

  var o = {
    p: 1,
    p: 2
  }; // Syntax error

2. Functions cannot have two parameters with the same name

  "use strict";

  function f(a, a, b) { // Syntax error

    return ;

  }

4.7 Disallow the octal expression

In normal mode, a number prefixed with 0 is treated as an octal number. For example, 0100 is 53 in decimal. In strict mode, this is not allowed.

  "use strict";

  var n = 0100; // Syntax error

4.8 Restrictions on arguments object

arguments is function's parameter object.

1. Cannot assign value to arguments object

 ã€€"use strict";

  arguments++; // Syntax error

  var obj = { set p(arguments) { } }; // Syntax error

  try { } catch (arguments) { } // Syntax error

  function arguments() { } // Syntax error

  var f = new Function("arguments", "'use strict'; return 17;"); // Syntax error

2. Arguments don't trace parameter change anymore

function f(a) {

    a = 2;

    return [a, arguments[0]];

  }

  f(1); // In normal mode, it's [2,2]

  function f(a) {

    "use strict";

    a = 2;

    return [a, arguments[0]];

  }

  f(1); // In strict mode, it's [2,1]

3. Disallow arguments.callee

  "use strict";

  var f = function() { return arguments.callee; };

  f(); // Error

4.9 Function declaration must be on the top level

The future JavaScript will introduce block scope, to conform with the new standard, strict mode only allows function declaration on top level of global scope or function scope.

  "use strict";

  if (true) {

    function f() { } // Syntax error

  }

  for (var i = 0; i < 5; i++) {

    function f2() { } // Syntax error

  }

4.10 Reserved words

Strict mode adds some new reserved words : implements, interface, let, package, private, protected, public, static, yield。

These words cannot be used as variable names.

    function package(protected) { // Syntax error

    "use strict";

    var implements; // Syntax error

  }

5. Reference links

- MDN, Strict mode
- Dr. Axel Rauschmayer,JavaScript's strict mode: a summary
- Douglas Crockford, Strict Mode Is Coming To Town

Author :  é˜®ä¸€å³° Source : http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html

Save as PDF Mark as read Mark as important
By clicking the "Mark as read" button, this article will be marked as read. It will be removed from the homepage's latest news and the article list on the "Technical article" page in following visits and it will be put to your read list which you can find in "Amin->Article read list". There you can unmark the read articles.
By clicking the "Mark as important" button, this article will be put to your important article list which you can find in "Amin->Article important list". Later when you want reread this article, it's easier for you to find it by checking the "Article important list".

Tags:JavaScript, Strict mode. Introduction   Read(707) Comment(0)

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Digg  Share on Tumblr    Delicious 

 Previous : Some useful Linux commands for teamwork
 Next : Hurry up!Upgrade your Windows 8 before February 1

  ::Related Articles

  ::Comment Zone

No comment for this article.

  ::Comment

Nickname  
Email 
Comment

:: Other versions

No other versions available yet.

:: Recent articles

:: Most read

:: Most commented

:: Contribute

Want to share with the world your understanding about technology? Want to record the process you solve a technical problem? Want to make the world benefit from your understanding and solution? Write them down. You make the world better, the world makes us better.

 Write article

:: Find us

Back to top