Why you should use strict with JavaScript

W

Many people “dislike” JavaScript for reasons that I cannot understand. I like it and it serves a purpose. JavaScript can be a very forgiving language. By that I mean it let’s you get a way with things that other languages, that are a little stricter, would not. This is where the “use strict” comes into play.

What is “use strict”

This was a new feature starting with ECMAScript5. Its goal is to make JavaScript, as the name says, a stricter, less forgiven language. It will throw exceptions when there are mistakes that may lead to problems. Similar to languages like PHP that compile at run-time, these errors would be thrown at that moment.

The best example I can think of is when you have not declared a variable before assigning it a value, e.g. foo = “bar”;. If you did not previously declare the variable with var foo; first, the browser will throw an exception allowing you to fix your unreliable code.

Two other nice examples are ensuring function parameters are unique: function fullName(name, name). As well as ensuring properties in an object are unique: var myObject = { name: ‘End Your If’, name: ‘Still end your if’ };. Both of these examples were cause exceptions and this is extremely helpful because it may be hard to spot and would cause endless problems.

For a more comprehensive list, see the article from the Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

About the author

By Jamie

My Books