Use Strict in JavaScript Explained with source code

strict mode example

Use strict mode to enforce modern JavaScript syntax and catch errors early:

‘use strict’;

“use strict” is a directive in JavaScript that enables “strict mode”. Strict mode is a way to opt in to a “secure” version of JavaScript. When in strict mode, JavaScript will validate your code more strictly and throw errors when it encounters “unsafe” or undefined behaviors.

Here’s an example of using “use strict”:

‘use strict’;

x = 10; // ReferenceError: x is not defined

(function() {

  ‘use strict’;

  y = 20; // ReferenceError: y is not defined

})();

In the above example, both x and y are not declared with var, let, or const and are therefore considered global variables. When the code is run in strict mode, a ReferenceError is thrown, indicating that the variables are not defined.

It is recommended to use “use strict” at the beginning of every JavaScript file to ensure that the code is executed in strict mode and to take advantage of its security benefits.