“Strict” Mode and Quality Code

In “sloppy” (or “normal”) mode, certain actions may not be permitted, but do not provide us with a reason by sending an error to the console.

We may expect we can delete variables or assign values to ‘read-only’ properties without using ‘strict’ mode because, well, nothing happens, but errors are super helpful!“strict” mode used in the global contextLine 3 doesn’t do much to our variable, but there are no errors thrown!Similarly, we cannot assign a new value to x in line 8, but the code fails silently.

However, when in a “strict” operating context, we can see exactly what we are doing wrong.

Assignments to non-writable globals like undefined, NaN, Infinity, etc also throw exceptions.

“Strict” mode also prevents the duplication of parameters in a function.

When we call the “notStrictSum” function, it returns a value of 16 even though we use “x” twice in our parameters.

“But, Chris — isn’t 4 + 5 + 6 = 15?” Yes, yes it is.

In this context, x is defined by our first parameter (x = 4), then reassigned (x = 5), then y is assigned (y = 6).

Our function then permits the execution of line 2, which returns 5 + 5 + 6.

However, we can see that our “strictSum” function throws a Syntax Error because it prohibits the use of duplicate parameters.

Additionally, “use strict” will prohibit the use of the ‘eval’ name/keyword and with(){} statements.

Sorry, were you using these?TL;DRWith that, I leave you with a nice little summary of the benefits of using “strict” mode in your Javascript files, provided by the techies over at geeksforgeeks:Strict mode makes several changes to normal JavaScript semantics.

Strict mode eliminates some JavaScript silent errors by changing them to throw errors.

Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.

Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.

It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).

It disables features that are confusing or poorly thought out.

Strict mode makes it easier to write “secure” JavaScript.

Resources for further reading:Strict modeJavaScript's strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of JavaScript, thereby…developer.

mozilla.

orgJohn Resig – ECMAScript 5 Strict Mode, JSON, and MoreEdit descriptionjohnresig.

comStrict mode in JavaScript – GeeksforGeeksStrict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating…www.

geeksforgeeks.

org.. More details

Leave a Reply