Solve JavaScript Error before it happens [strict mode]

JavaScript Dec 24, 2014

What is strict mode

The fifth edition of the ECMAScript specification introduced Strict Mode. Strict Mode prevents certain actions from being taken and thrown out as errors. It protects you from the most common and egregious aspects of the language. This is the primary advantage. The second one is it will fix the issues that could make JavaScript engine to optimise your code. There by, the strict code sometimes runs faster than a not strict code. Also strict mode throws errors on questionable syntax which could be defined as a different action in the future ECMAScript specification.

How to enable strict mode

You could apply strict mode to complete file or individual functions. You cannot apply them in a block statement under braces.

JS strict script files

For an entire script you have to write the exact line

“use strict”;

or

‘use strict’;

before any other statement.

// The below script follows strict mode syntax
'use strict';
var x = “Script runs in strict mode”;
function testFunction(){
    alert(x);
}

Warning: Note that when you make a script strict and if you include this script into a non-script mode script, then the latter also becomes a strict script because the first line of it includes the 'use strict'; syntax.

JS strict functions

In functions as well use the ”use strict”; at the first line of the function

function testFunction() {
    ‘use  strict’;
    alert('This function runs in script mode');
}

What does strict mode do

Strict mode changes the way the browser evaluates your JS code and also changes the way the syntax of your JS code will behave.

There are quite a few mistakes that usually are not noticed in the novice friendly JavaScript. Strict mode helps you uncover them:

Prevents implicit globals

Variables must be declared before they can be assigned to. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript.

Strict mode makes it impossible to accidentally create global variables.

'use strict';

age = 10;  // Assuming age is not declared.
           // Throws ReferenceError: age is not defined

Unique properties name

Strict mode requires that all properties named in an object literal be unique.

'use strict';

var customer = { first_name: “First Name”, first_name: “Second_Name” }; // SYNTAX ERROR

Unique parameters name

Strict mode requires that all parameters to a function are unique

'use strict';

function onLogin (id, first_name, first_name)  { // SYNTAX ERROR
    return first_name + second_name;
}

Errors for immutables

In Strict mode, assignments to non-writable or getting-only property or creating a new property on a non-extensible object will throw an error.

'use strict';

var xobj = {};
Object.defineProperty(xobj, ‘x’, { value: “Script Name”, writable: false });
xobj.x = “New Name”;  // TYPEERROR

var yobj = { get y() { return “Name”; } };
yobj.y = “New Name”; // TYPEERROR

var fixedobj = {};
Object.prventExtensions(fixedobj);
fixedobj.name = “Name”; // TYPEERROR

Eval scope

In normal code eval("var x;") introduces a variable x into the surrounding function or the global scope. But in strict mode, any variables or functions created inside of eval() stay inside of eval(). You can, however, return a value from eval() if you wish to pass a value back out:

'use strict';

var sum = eval("var x = 30, y = 40; x + y");

// Works in strict and non-strict mode
alert(sum);

// Strict mode, throws an error because x is undeclared
alert(x);

Eliminates this coercion

In Strict Mode, the value of this will not be auto-coerced to an object. If the first argument to call or apply is null or undefined, the this value of the invoked function will not be converted to the global object.

'use strict';

window.name = "atatus";
function testFunction() {
    alert(this.name);
}

// Throws an error in strict mode, "atatus" otherwise
testFunction();

// Throws an error in strict mode, "atatus" otherwise
testFunction.call(null);

Undeletable properties

Deleting undeletable properties and functions throws error

'use strict';

// Deleting Object.prototype
delete Object.prototype; // TYPEERROR

// Deleting a variable, a function, or an argument will result in an error.
var name = "test";
function testFunction(){}
delete name; // SyntaxError
delete testFunction; // SyntaxError

function testFunction2(arg) {
    delete arg; // SyntaxError
}

Prohibits with

The strict mode eliminates the with statement. It is now considered invalid JavaScript syntax and will throw a syntax error when it appears in strict mode code.

'use strict';

// Causes a syntax error in strict mode
var object = {name: 'atatus'};
with (object) {
    alert(name);
}

Prohibits arguments.callee

In strict mode, arguments.callee is considered invalid JavaScript syntax.

'use strict';

// Causes a syntax error in strict mode
function (testInt) {
    if (testInt-- == 0)
        return;
    arguments.callee(testInt--);
}

Prohibits octal syntax

Strict mode prohibits octal: Assigning an octal value to a numeric literal, or attempting to use an escape on an octal value.

'use strict';

var x = 010 + 100; // SYNTAXERROR due to octal variable 010
var testescape = \010; // SYNTAXERROR

Some more strict checks are encompassed in strict mode, such as you cannot use eval, arguments as an identifier (variable or function name, parameter name, and so on). It blocks certain future possible ECMAScript keywords from being used such as implements, interface, package, private, protected, public, static, and yield.

Our Recommendation

Always “use strict” where and when possible. This will avoid your code from running into all sorts of problems, as one would know that maintenance of the code is the most difficult task rather than writing new code.

And for any errors that cannot be caught by strict will be caught by Atatus.

Atatus makes error tracking simpler on your live web applications along with user interactions being captured that lead to the error. This helps you in resolving the errors much faster (similar to what strict would help you for).

Also integrate with your team chat and tracking systems. Try out the free 14 day trial – no credit card required.

Monitor your entire software stack
Gain end-to-end visibility of every business transaction and see how each layer of your software stack affects your customer experience.
Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.