What is JavaScript Strict Mode?

0

JavaScript is a forgiving language. Some of its syntax is optional, and the language recovers errors more gracefully than many others. But with that getting started comes a penalty: it may be easier to introduce bugs, and inconsistent code is harder to read.


Fortunately, if you want to exercise more discipline, there is an easy way to do it: Strict mode. Strict mode is a way to tell JavaScript to react more decisively when it encounters problems in your code.


What is a strict mode?

Several languages ​​use the concept of strict mode: a mode that evaluates and executes code more rigorously. You may be familiar with the strict HTML doctype, which deprecates certain elements and attributes.

Perl, another interpreted scripting language, has long had its own strict mode. This mode prohibits certain types of unsafe expressions.

How to use strict mode in JavaScript?

Inside a script, place a “use strict” statement at the very top, before any other statement:

VIDEO OF THE DAY MAKEUSE
// this entire script will be in strict mode
'use strict';

Note that you can include a comment before this one, but no instructions. You can enable strict mode in a JavaScript file or at the start of a script block in an HTML file. You can also activate strict mode function by function:


function strict() {
// Function-level strict mode syntax
'use strict';
return "This function is strict";
}
function loose() {
return "This function is NOT strict";
}

Once you’ve enabled strict mode, be sure to test your code. If you work with the web, open a JavaScript console so you can identify any new errors.

What is the strict mode of JavaScript for?


JavaScript code in a MacBook Pro

In short, strict mode will be less forgiving for certain types of problematic code. Rather than ignoring the issues and continuing to run, some errors will stop the script. This is often safer than continuing under unwanted circumstances.

Prevents accidental globals

The best example that strict mode protects against is the creation of accidental global variables. In normal execution, this code:


myVar = 17;

It will create a property named myVar on the global object, assuming you haven’t already declared myVar. In a web browser, the global object is usually window:

console.log(window.myVar);
>> 17

However, if you include a “use strict” statement, you will see an error in the console, something like:

Uncaught ReferenceError: myVar is not defined

The reason this is so useful is that it detects a common case of typo. It is easy to type the name of a variable incorrectly, and many languages ​​would catch us on such an error.

But JavaScript, by default, simply assumes the scope of the global object and continues as if nothing happened. Some code may intentionally depend on this behavior, which you should be aware of when deciding to use strict mode.

See also: How to keep your code clean with object wrapping


Make failure explicit

Some behaviors in JavaScript fail, but they do so silently. You might not be aware of these errors unless you specifically research them. For example, NaN is a special property of the global object that represents an invalid number. This property is read-only, but you can always try writing to it:

NaN = 2;
>> 2

But even though it looks like this mission was successful, it didn’t:

NaN
>> NaN

In strict mode, you will get a real error telling you that you cannot assign to NaN. This code uses a function so that you can demonstrate strict mode in the console:

javascript
function badNaN() { "use strict"; window.NaN = 2; }
>> undefined
badNan()
>> Uncaught TypeError: Cannot assign to read only property 'NaN' of object '#'
at badNaN (:1:46)
at :1:1

This is a classic example that shows that while ignorance can be bliss, sometimes it’s best to know if something is wrong.

Warns of duplicate settings

The last example deals with a little-known feature of JavaScript. You might be surprised to learn that parameter names don’t have to be unique:

function dupeParam(a, a, c) { console.log(a); }
>> undefined
dupeParam(2, 4, 8)
>> 4

Note that JavaScript assigns the last value to a duplicate parameter. However, this behavior is not particularly useful. In fact, it would be more useful for JavaScript to tell us that this is an error, and that’s exactly what strict mode does:

function dupeParam(a, a, c) { "use strict"; }
<< Uncaught SyntaxError: Duplicate parameter name not allowed in this context

Good practices and the means to enforce them go hand in hand. In some contexts, like a professional programmer role, you’ll want to exercise as much discipline as possible. Even if you are only working on an amateur open source project, the maintainer may prefer to use strict mode by default.


Ultimately, it’s up to you, but it helps to know that a helping hand is available. As a programmer, you should always be on the lookout for best practices and what you can do to apply them.


good programmer
10 basic programming principles every programmer should know

Your code should be clear and easy to maintain. Here are several other programming principles to help you clean up your act.

Read more


About the Author


Source link

Share.

About Author

Comments are closed.