What is 'use strict' in JavaScript for?

Answer

"use strict" is a directive in JavaScript that enables strict mode, a stricter set of rules for writing JavaScript code. It helps catch potential bugs, enforces safer coding practices, and improves performance in some cases.


How to Use "use strict"

Globally

Placed at the top of a script file, it applies strict mode to the entire file.

'use strict';
x = 10; // Error: x is not defined

Function Scope

Placed at the beginning of a function, it applies strict mode only within that function.

function myFunction() {
  'use strict';
  y = 20; // Error: y is not defined
}
myFunction();

Key Features and Benefits of Strict Mode

  1. Prevents the Use of Undeclared Variables
'use strict';
a = 10; // Error: a is not defined
  1. Disallows Duplicating Parameter Names
'use strict';
function example(a, a) {} // Error: Duplicate parameter name
  1. Eliminates Silent Errors

Some operations that fail silently in non-strict mode throw errors in strict mode.

'use strict';
delete Object.prototype; // Error: Cannot delete property
  1. Prevents this from Defaulting to window

In functions, this defaults to undefined instead of the global object.

'use strict';
function example() {
  console.log(this); // undefined
}
example();
  1. Makes Code Easier to Optimize

Some optimizations are easier for JavaScript engines to perform in strict mode.

  1. Reserved Keywords for Future

Disallows the use of keywords like implements, interface, and private, ensuring compatibility with future JavaScript versions.

When to Use "use strict"

MDN Web Docs: Strict Mode