Strict mode in JavaScript

By | June 25, 2023

For a long time, JavaScript had no compatibility issues because in every new version release old functionality were not changing. But it was not good as if there were any issue with old language, then old functionality must be modify accordingly to resolve that issue.

In this regard, ECMAScript 5 (ES5) has appeared in year 2009. It release new features and modified some of the existing ones for the first time. But, you will require a special directive: “use strict” to specify that you are using updated version of JavaScript. If you will not add “use strict” in your code, then such modifications are off by default.

“use strict”
This directive looks like a string: “use strict” or ‘use strict’. You need to inlcude it it Top of the Script to work correctly, otherwise it will be ignored and will not work.

For example:

"use strict";

// this code works the modern way
...

You can also use it as first line inside a function.

If you will include it middle of the script, then script mode will be ignore and will not be enable. So, strictly include “use strict” or ‘use strict’ in top of script to enable script mode.

Note that only comments may appear above “use strict”. Also, note that there is no way to revert the engine to old behavior once you enable strict mode.

Browser console
Browser console also does not enable strict mode by default, so you need to tell the browser to enable it.

But you need to use it along with code as top line of “use strict”. So you can do it by using multi-line code insertion.

You can hit Shift+Enter to input multiple lines

'use strict'; <Shift+Enter for a newline>
//  ...your code
<Enter to run>

It works in most browsers, namely Firefox and Chrome.

If it does not work in your browser, then you can use it kind of wrapper to ensure work correctly. Include ‘use strict’ as first line of function:

(function() {
  'use strict';

  // ...your code here...
})()

You can “use strict” at the top of your scripts. But, if your code is organized into classes and modules, you can omit it. Becasue Modern JavaScript supports “classes” and “modules” that enable use strict automatically.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.