Sobes.tech
Junior

Why is 'use strict' used in JavaScript?

sobes.tech AI

Answer from AI

'use strict'` is a directive that enables strict mode in JavaScript.

Strict mode:

  • Prohibits the use of undeclared variables.
  • Disables implicit binding of this to the global object in functions.
  • Throws errors when assigning to read-only properties.
  • Prevents deleting non-deletable properties.
  • Disables with.
  • Prohibits duplicate parameter names in functions.
  • Simplifies code optimization.

Advantages of using 'use strict':

  • Improves code readability and maintainability: Detects potential errors early.
  • Prevents accidental errors: Disallows dangerous or undesirable constructs.
  • Ensures future compatibility: Some features of future JavaScript versions may require strict mode.

Strict mode can be applied to an entire script or individual functions by placing the directive at the first line.

// Applying to a function
function myStrictFunction() {
  'use strict';
  // Code in strict mode
}

// Applying to the entire script
// Must be the first line of the file
'use strict';
// Code in strict mode