JavaScript’s strict mode: a summary

[2011-01-20] dev, javascript, jslang
(Ad, please don’t block)
Update 2011-10-28: JavaScript: Why the hatred for strict mode?

Douglas Crockford has written a nice post on the strict mode (source: Matthias Hölzl). The following is a summary of it.

What it is

  • You can selectively switch on strict mode for your JavaScript code and enable a more modern version of it. This kind of opt-in allows JavaScript implementors to evolve the language without sacrificing compatibility.
  • Strict mode is part of the ECMAScript 5 standard.
  • You can enable strict mode for a complete file or a single function:
    • Complete file: put the line "use strict"; at the beginning of the file. As a statement, this does nothing and will be ignored by legacy JavaScript interpreters.
    • Single function: using the mode for a complete file might break some functions in it, so by putting the line mentioned above at the beginning of a function, you can enable strict mode for it.
  • Safety is one of the main motivations for strict mode (see end of Crockford’s post)

Most important changes

  • Improved safety: very limited use of eval(), with statement not permitted.
  • Global variables must be explicitly declared (no more auto-creation). This helps to prevent typos.
  • Calling constructor functions without new: Prior to strict mode, this was bound to the global object which resulted in properties being added to that object. In strict mode, this will be bound to undefined and an exception will usually be thrown if constructors are called without new.
  • Noisy failure: Attempting to change a read-only property throws an exception. So does attempting to delete a non-configurable property.
  • No more octal numbers: As a remnant from JavaScript’s C inheritance, numbers with leading zeros were interpreted as octal. Now 0100 really is 100 and not 64. And 08 is not an error, any more.
  • Arguments object: The properties arguments.callee and arguments.caller have been eliminated (for safety reasons: it keeps them secret from foreign code).
  • Function parameters: No more duplicate parameter names or variables that have the same name as a parameter.

Related reading