< FrankJS />

Don't Be Sloppy; Use Strict Mode in JavaScript

JavaScript, by default, allows for things that many may deem undesirable. JavaScript's strict mode is a restricted variant of JavaScript, created with the intention of attenuating some of these aspects. When compared to non-strict mode, itĀ has different semantics.

While most modern browsers do support strict mode, you also have the added complexity of browsers that do not support strict mode running strict mode code with different behavior from browsers that do. According to Mozilla documentation, "Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally."

Strict mode helps us with our coding by making some normally silent errors throw noticeable errors as well as prohibiting us from using certain syntax. The idea is that by using strict mode we setup guard rails to help us write code with fewer bugs, better security, and more compatibility with future revisions of ECMAScript.

Strict mode can be applied toĀ entire scriptsĀ or toĀ individual functions.

Some key characteristics of strict mode include:

  • It doesn't apply to block statements enclosed inĀ {}Ā braces.

  • For an entire script, use 'use strict';

  • For individual functions, within your function, place 'use strict'; as the first line. For example:

function sampleFunction() { 'use strict';

console.log('cool');

}

  • JavaScript modules are automatically in strict mode, with no statement needed to initiate it.

  • Throws an error when you attempt to create global variables.

  • An assignment that normally would fail silently, will throw an error in strict mode. This includes assignment to a non-writable global or property, assignment to a getter-only property, or assignment to a new property on a non-extensible object.

  • Where before, the attempt to delete an undeletable property would simply have no effect, strict mode instead makes attempts throw an error.

  • Function parameter names must be unique.

  • Forbids setting properties on primitiveĀ values, throwing a TypeError. Without strict mode, attempting to is simply ignored.

  • Prohibits usingĀ with.

  • The following identifiers become reserved keywords: These words are implements, interface, let, package, private, protected, public, static, and yield. You're prevented from naming or using variables or arguments with these names.

As always, make sure toĀ test your code in browsers that do and don't support strict mode.

Frank J Santaguida, 2022