Strict Mode in JavaScript

JavaScript1 min read
Strict Mode in JavaScript
JavaScriptStrict ModeError HandlingWeb Development

Learn how to enable JavaScript's strict mode globally or within functions and see examples that help prevent common mistakes like undeclared variables.

What is Strict Mode in JavaScript?

Strict mode in JavaScript allows us to enforce a more strict set of rules and behaviors in our code. It helps in catching silent errors, preventing accidental global variables, and disallowing duplicate parameter names.

Enabling Strict Mode

  • Strict mode can be enabled both globally and at the function level.

1. Global-Level Strict Mode

  • To enable strict mode globally, add "use strict"; at the top of your JavaScript file like this:
"use strict"; let username = "John Doe"; console.log(username); // No error

Example:

  • If you assign a value to a variable without declaring it (without strict mode):
username = "John Doe"; console.log(username); // No error in non-strict mode
  • Enabling strict mode will cause an error for undeclared variables:
"use strict"; username = "John Doe"; console.log(username); // Error: username is not defined

2. Function-Level Strict Mode:

  • To enable strict mode only within a function, add "use strict"; at the top of the function:
function myFunction() { "use strict"; let x = 20; // Variable declared and assigned a value console.log(x); // No error } myFunction();

Example:

  • If you assign a value to a variable without declaring it inside a strict mode function:
function myFunction() { "use strict"; x = 20; console.log(x); } myFunction(); // Error: x is not defined
  • Outside of strict mode functions, variables can still be accessed without declaration:
function myFunction() { "use strict"; x = 20; console.log(x); } myFunction(); // Error: x is not defined x = 20; // No error outside strict mode console.log(x); // 20