javascript strict mode - strict mode

Javascript Strict Mode — Walking The Straight Path

Writing reliable computer software is the primary goal of professional programmers. By default, Javascript is a weakly typed language — to support quick prototyping of ideas — that comes with a "strict mode" which may be enabled to catch compile-time errors and exceptions.

The public release of strict mode (in 2011) was as part of the Javascript version 5 specification. This mode counters the default permissive style with a less flexible interpretation that restricts some syntax from being used and throws more exceptions on possibly ambiguous code. This reduced, safer feature set results in more reliable and predictable software at the cost of greater defensive programming. Specifically, Javascript strict mode:

  • prevents alternate octal notations
  • prevents deleting undeletable properties
  • prevents duplicate argument names
  • prevents future naming issues
  • prevents invalid variable assignments
  • prevents unintentional global variables

Invoking Javascript Strict Mode

Javascript strict mode is optionally available for some scopes and always enabled for others, as shown:

enforcement scopestrict mode options
script-wideoptionally available
function-by-functionoptionally available
modulesalways strict
classesalways strict

Note please that strict mode applies only to script-wide or to individual functions. Bare block statements enclosed in braces — {} — do not take strict mode.

Enabling Script-Wide Strict Mode

// Script-wide strict mode syntax
"use strict" ; // alternatively, 'use strict'
// script steps follow

Enabling Function-by-Function Strict Mode

function strictFunction( arguments ) { // strict
    "use strict"
    // function steps follow
}

function sloppyFunction( arguments ) { // not strict
    // function steps follow
}

What Does Strict Mode Actually Do?

Strict mode changes some previously-tolerated mistakes (which generate informative warnings that could be ignored) into errors (that generate progress-halting fatal errors). Because JavaScript was designed to be easy for novice developers to learn and prototype, it makes forgiving assumptions about what was meant. While this smoothes the way to getting a program running, these assumptions may mask conceptual mistakes that cause far worse problems in the future. Strict mode treats these mistakes as errors so that the programmer discovers, understands, and fixes these issues immediately. It’s tough love.

Prevents Unintentional Global Variables

In the default, permissive Javascript mode, mistyping a variable name simply creates a new variable in the global namespace.

'use strict';

var length = 180 ;

lenght = 90 ; // strict mode flags this typo as an error

Prevents Invalid Variable Assignments

Javascript strict mode makes assignments which would silently fail in permissive mode to throw a blocking exception, including, variable assignments to:

  • non-writable globals
  • non-writable properties
  • getter-only properties
  • new property of a non-extensible object

Prevents Deleting Undeletable Properties

Attempting to delete a property to which you don’t have permissions is silently ignored in permissive mode; not so in strict mode.

'use strict' ;

delete Object.prototype ; // strict mode TypeError

Prevents Duplicate Argument Names

Strict mode requires that function argument names be unique. In permissive mode a duplicated argument hides previous identically-named arguments, most typically caused by a distracted programmer making a typo of a variable name.

The following example shows a defensive programming technique for Javascript’s ability to take any number of arguments (regardless of the number actually declared) being subverted by a typo in the argument list — a typo discovered and flagged in strict mode.

'use strict' ;

function mean( a, b, b ) { // should've been a, b, c
    var total ;
    for ( var i = 0, j = arguments.length ; i < j ; i++ ) {
        total += arguments[i] ;
    }
    return total / arguments.length ; // mean average
}

Prevents Alternate Octal Notations

In permissive mode, numbers beginning with a zero (such as the permissions string 0644) are considered as an octal number if all digits are less than eight.

Octal escape sequences can be used to represent characters by extended-ASCII character code; for example \45 is equivalent to the character %.

Strict mode prevents these valid alternate forms of expressing octal numbers in favor of prefixing the octal number with 0o, as in var c = 0o123 ;.

The rationale for this is that novice developers may use a leading zero as an alignment device, not realizing it has a semantic meaning, as in:

'use strict' ;

var sum = 001 + // so nicely lined up...
          012 +
          123 ;

Before you laugh, this alignment technique has been done with IP addresses too; changing 127.0.0.1 to 127.000.000.001 completely fails because each tuple is then interpreted as octal rather than decimal.

Prevents Future Naming Issues

Javascript — like other software packages — evolves. (Version 11 is the current release; 12 was finalized in June 2021.) With future plans always under consideration strict mode makes an attempt to ease the transition by applying some restrictions. For example, the following identifiers have become reserved keywords: implements, interface, let, package, private, protected, public, static, and yield. In strict mode neither variables nor arguments with these names may be used.

Conclusion

This blog post Javascript strict mode, how it assists programmers in writing error-free code by identifying and preventing common issues (in both current and future Javascript versions).

Start Learning

To learn more about Javascript, check out other Javascript blog posts and enroll in our Javascript Nanodegree programs, including Intermediate Javascript.