Follow @endyourif rss Facebook LinkedIn

Why you should use strict with JavaScript Why you should use strict with JavaScript

Published on Jan 24, 2020

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:

Tags: Javascript | JavaScript

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP