Error-Checking: Strict Mode in JavaScript

In this article, I shall talk about the strict mode of JavaScript. Strict mode is the method to introduce better error-checking into the JavaScript code, as JavaScript is a loosely-typed scripting language.

Languages like C++, Java or C# etc., are the strict-typed languages. For example, the compiler for the aforementioned languages prompts errors if a variable is used before even defining it.

With the improvement in JavaScript, especially from ECMA Script 5 onward, we can write the code in strict mode by using the keywords use strict.

Whenever you want to write your JavaScript code in the strict mode, use use strict at the top of your code to tell the browser or JavaScript interpreter that you want to do programming in the strict mode.

Usage

"use strict";

var a = 1; // valid in strict mode
b = 1; // invalid in strict mode

Notice the following in above code:

  1. At the top use strict is used to specify that you want strict mode for your program.
  2. As b is declared without var, let or const, the strict mode will give you an error in this case.

Top 5 Things NOT Allowed in Strict Mode

1: Use of Reserved words is forbidden

Let me first give you an example:

"use strict";
var for = 1; // error
var while = 1; // error

In the above example, as you can see, I have used the words for and while, which are actually the reserved words of JavaScript used in loops.

2: Undefined Variables are not allowed

The example is:

"use strict";

x = 1; // error

As you can see above that the keyword var before x = 1 is missing. This will give you an error!

3: Don't try to write the read-only properties

"use strict";

var array = [1 ,2 ,3 ,4, 5];
array.length = 10; // error

In the above example, array.length is the read-only property. It is forbidden to rewrite it.

4: Don't you identical names as parameters in JavaScript function

"use strict";

function multiply(val, val){return val * val }; // error

In the above example, as you can see the parameters of this function. val is duplicated in the second argument as well.

5: Same property names of the Same object are prohibited

First let me give you an example:

"use strict";

var objectCustom = { a: 100, a:"test strict mode" }; // error

In the above example, as you can see that the object named objectCustom has two properties, and both of those properties have the same names, which is a. Such kind of names' duplication is not allowed in strict mode.

Summary

In this article, I have discussed about the strict mode of JavaScript, its usage, and the things which are not allowed under strict mode. I hope you understand the crux of this subject-matter. That is it for this article!

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?