Introduction
Strict mode in JavaScript is a modern way of writing the JavaScript code. This is a new feature in ECMAScript 5 that prevents most of the Javascript silent errors by changing them into throw errors.
What we will cover
- How to use strict mode
- The benefits of strict mode
- Different levels of using the strict mode
How to use strict mode
“use strict” is the statement that instructs the browser to use the strict mode. Let 's check the difference between Normal mode and Strict mode with an example.
Default Mode
Consider the below code.
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Untitled</title>
- </head>
- <body>
- <label id="message"></label>
- <script>
- var foo="hello";
- x=10;
- function baz()
- {
- foo="Hello from function";
- bam="Hello from bam"
- document.getElementById('message').innerHTML=bam;
- }
- baz();
- </script>
- </body>
- </html>
As per the code in default mode, the function baz will assign the bam identifier value to the inner HTML of the label. You can see the result of executing this code as below.
figure 1: In Default mode
Even though the variable bam is not declared, the value can be initialized to the variable which is somewhat annoying in the normal identical way of writing JavaScript.
Strict Mode
Consider the below code.
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Untitled</title>
- </head>
- <body>
- <label id="message"></label>
- <script>
- 'use strict';
- var foo="hello";
- x=10;
- function baz()
- {
- foo="Hello from function";
- bam="Hello from bam"
- document.getElementById('message').innerHTML=bam;
- }
- baz();
- </script>
- </body>
- </html>

Join the conversation! Your thoughts help the community grow.