Comments

What is Strict Mode in JavaScript?

JavaScript Strict Mode is a new feature in ECMAScript 5 that enables you to code a program, or a method, in a “strict” operating context. It is a way to opt into a restricted variant of JavaScript. Hence, implicitly opting-out of “sloppy mode”. This strict context prevents from taking some actions. As a result, it throws more exceptions.

The statement “use strict” instructs the browser to use the strict mode. It is a reduced and safer feature set of JavaScript. Another point is that it fixes some mistakes that prevent engines to perform optimizations. Moreover, it forbids some syntax that might be used in future versions of the ECMAScript.

Major Advantages of using JavaScript Strict Mode

  • By changing errors to throw errors, strict mode removes certain JavaScript silent errors.
  • Strict mode repairs mistakes that make it difficult for JavaScript engines to perform optimizations. (It can sometimes execute faster than identical code that’s not strict mode.)
  • Strict mode forbids certain JavaScript syntax. (In future versions of ECMAScript.)
  • When relatively “unsafe” actions are taken, it prevents or throws errors. (Such as gaining access to the global object).
  • It restricts features that are unclear or poorly thought out.
  • Strict mode makes it easier to write “secure” JavaScript code.

Invoking/Using JavaScript strict mode

Strict mode can be invoked in two ways:

  1. It can be defined in global scope for the entire script
  2. It can be defined as individual functions.

Note that: – Strict mode doesn’t work with block statements enclosed in {} braces. Therefore, eval code, Function code, event handler attributes, strings passed to WindowTimers.setTimeout(), and related functions are entire scripts, and invoking strict mode in them works as expected.

Using JavaScript strict mode for the entire script

While invoking strict mode for an entire script, you need to put the exact statement “use strict”; (or ‘use strict’ ) before any other statements. As a result, the entire script is in “strict” operating context taking advantage of strict mode benefits. The example can be seen below:

// Whole-script strict mode syntax
 'use strict';
 let script = " This is strict mode script!";

Therefore, this syntax has a flow that has already flawed a major site: it isn’t possible to thoughtlessly concatenate conflicting scripts. You can consider concatenating a strict mode script with a non-strict mode script. As a result, the entire concatenation looks strict. Moreover, the inverse is also true where non-strict plus strict looks non-strict. More importantly, the concatenation of scripts is never ideal. But, if you must, you should consider enabling strict on a function-by-function basis (at least during the transition period).

On the other hand, you can also impose the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. As a result, this eliminates the concatenation problem. It implies that you have to explicitly export any shared variables out of the function scope.

Using JavaScript Strict mode for functions

To invoke strict mode for a function, define the exact statement “use strict“; (or ‘use strict’😉 in the function’s body before any other statements. You can get a better understanding of strict mode with the example below.

function strictFunc() {
  // Function using strict mode syntax
  'use strict';
  function insideFunc() {
     return 'is nested function';
  }
  return " This is function is in strict mode context and so is " + nested();
}

function nonStrictFunc(){
  return "This function is not in strict mode context";
}

Here, the function strictFunc() is in strict mode context because “use strict” statement is defined inside of it. The function nonStrictFunc() is not in strict mode context because the function doesn’t contain any “use strict” statement defined within it neither it is defined globally.

Using JavaScript Strict mode for modules

ECMAScript 2015 introduced JavaScript modules. Therefore, a 3rd way of invoking strict mode came with it. Here, the entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.

function strictFunc() {
    // because this is a module, it is strict by default
    console.log(“ the contents inside are automatically in strict mode”);
}                                    
export default strictFunc;

Here, the module defined as strictFunc() is automatically in strict mode. It is not needed to use “use strict” statement.

Strict mode in browsers

The major browser such as chrome, Firefox, opera, etc. now implement strict mode. However, you should depend on them blindly. Since there still are numerous Browser versions used in the wild that only have partial support for strict mode or do not support it at all (e.g. Internet Explorer below version 10), you should use in carefully with browsers. Strict mode makes semantic changes. As a result, relying on those changes will cause mistakes and errors in browsers which don’t implement strict mode. You need to exercise caution in using strict mode and back up reliance on strict mode with feature tests that check whether relevant parts of strict mode are implemented.

Finally, make sure to test your code in browsers that do and don’t support strict mode. If you test only in browsers that don’t support strict mode, you’re very likely to have problems in browsers that do, and vice versa. Hence, precautions are necessary while using strict mode in the browsers.

Changes in strict mode

Strict mode alters and affects both syntax and runtime behavior. These changes generally fall into these categories:

  • Changes which converts mistakes into errors (as syntax errors or at runtime),
  • The changes simplifying how the particular variable for a given use of a name is computed,
  • Changes which simplify eval and arguments,
  • The changes making it easier to write “secure” JavaScript, and changes anticipating future ECMAScript evolution.

Converting mistakes into errors

Strict mode changes some previously-accepted mistakes into errors. Strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to “work” (although future failure is possible: likely, in modern JavaScript).

'use strict';
// Assuming a globalvariable mistypedVariable exists
mistypeVariable = 17;             
// this line throws a ReferenceError due to the
// misspelling of variable

Strict mode makes assignments which would otherwise silently fail to throw an exception. For example, NaN is a non-writable global variable. In normal code assigning to NaN does nothing; the developer receives no failure feedback.

 

'use strict';

// Assignment to a non-writable global

      var undefined = 5;             // throws a TypeError
      var Infinity = 5;              // throws a TypeError

// Assignment to a non-writable property

      var obj1 = {};
      Object.defineProperty(obj1, 'x', { value: 42, writable: false });
      obj1.x = 9;                    // throws a TypeError

// Assignment to a getter-only property

      var obj2 = { get x() { return 17; } };
      obj2.x = 5;                   // throws a TypeError

// Assignment to a new property on a non-extensible object

      var fixed = {};
      Object.preventExtensions(fixed);
      fixed.newProp = 'ohai';      // throws a TypeError

Strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect):

'use strict';
delete Object.prototype; // throws a TypeError

Simplifying variable uses

Strict mode simplifies how variable names map to particular variable definitions in the code. Many compiler optimizations rely on the ability to say that the storing of variable X in that location: this is critical to fully optimize JavaScript code. Strict mode prohibits with. The problem with with is that any name inside the block might map either to a property of the object passed to it, or to a variable in surrounding (or even global) scope, at runtime: it’s impossible to know which beforehand. Strict mode makes with a syntax error, so there’s no chance for a name in a with to refer to an unknown location at runtime:

'use strict';
var a = 0003;
with (obj) { // !!! syntax error
  // If this weren't strict mode, would this be var x, or
  // would it instead be obj.x?  It's impossible in general
  // to say without running the code, so the name can't be
  // optimized.
  a;
}

Makes eval and arguments simple to operate

Strict mode makes arguments and eval less bizarrely magical. Both involve a considerable amount of magical behavior in normal code: eval to add or remove bindings and to change binding values, and arguments by its indexed properties aliasing named arguments. Strict mode makes great strides toward treating eval and arguments as keywords, although full fixes will not come until a future edition of ECMAScript.

'use strict';
eval = 17;
arguments++;
++eval;
var obj = { set p(arguments) { } };
var eval;
try { } catch (arguments) { }
function x(eval) { }
function arguments() { }
var y = function eval() { };
var f = new Function('arguments', "'use strict'; return 17;");

there is no longer support for arguments.callee. In normal code, arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function. arguments.callee for strict mode functions is a non-deletable property which throws an error when set or retrieved:

'use strict';
var strict = function() { return arguments.callee; };
strict(); // throws a TypeError

Making JavaScript Secure

Strict mode makes it easier to write “secure” JavaScript. Some websites now provide ways for users to write JavaScript which will be run by the website on behalf of other users. JavaScript’s flexibility makes it effectively impossible to do this without many runtime checks. Certain language functions are so pervasive that performing runtime checks has a considerable performance cost.

'use strict';
Function strict() { return this; }
console.assert(strict() === undefined);
console.assert(strict.call(2) === 2);
console.assert(strict.apply(null) === null);
console.assert(strict.call(undefined) === undefined);
console.assert(strict.bind(true)() === true);

First, the value passed as this to a function in strict mode is not forced into being an object. For a normal function, this is always an object: either the provided object if called with an object-valued this; the value, boxed if called with a Boolean, string, or number this; or the global object if called with an undefined or null this. (Use call, apply, or bind to specify a particular this.) Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that “secure” JavaScript environments must restrict. Thus for a strict mode function, the specified this is not put into an object, and if unspecified, this will be undefined.

Summary

Using JavaScript Strict Mode is good news because JavaScript allows many ‘poor coding’ practices without triggering exceptions. This can lead to pages, components, and entire applications failing once they are shipped to production because developers were unaware they had improperly used syntax or a bad pattern. It helps us make the code more secure and easier. The simplicity in the use of variables gives coders benefits of prevention from different syntax errors. You can try using strict mode both in the entire script and in individual function and see the changes to yourself.

If you are looking to master JavaScript, I highly recommend Mosh’s courses on JavaScript. This link has several JS courses by Mosh.

I hope you enjoyed this article!

Krissanawat is Nomad Web developer live in Chiangmai passionate on React and Laravel
Tags: ,

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts