Exploring JavaScript Strict Mode

Exploring JavaScript Strict Mode

How Strict Mode Shapes Cleaner Code

What is Strict Mode?

JavaScript has a feature called ‘strict mode’.

It was introduced in ECMAScript 5 (ES5), and it helps to catch common errors that otherwise would be ignored.

For instance, in strict mode, using undeclared variables is not allowed.

Declaring Strict Mode

If you want to declare strict mode, you can do it for an entire script or an individual function.

Strict mode for an entire script:

Strict mode for an individual function:

Make sure you are enabling ‘use strict’ at the beginning of a script or a function, otherwise it will not be recognized!

What Mistakes Does Strict Mode Catch?

Enabling strict mode in JavaScript helps quite a lot in the development process.

It catches many common coding mistakes and unsafe practices, for example, the use of undeclared variables, as mentioned before.

Here are more examples of what is not allowed in strict mode:

  • Use of undeclared objects.

  • Deleting variables, objects, or functions.

  • Duplicating a parameter name.

  • Using some words for variable names that are already reserved for future ECMAScript versions.

Strict Mode in Modern Development

While the introduction of strict mode in ECMAScript 5 helped a lot in the earlier days, it’s not as used as it was before.

In modern development, it is more practical to use JavaScript modules that come in a strict mode automatically.

Today, enabling strict mode is mainly helpful for older projects or for projects that use a mix of old and modern JavaScript.