PXProLearnX
Sign in (soon)
JavaScriptmediumconcept

What is the purpose of `use strict`?

Explanation:

use strict is a directive introduced in ECMAScript 5 that allows you to opt into a restricted variant of JavaScript. Its purpose is to catch common coding errors and "unsafe" actions, such as defining global variables. This mode helps you write more secure and optimized JavaScript code by preventing certain actions that are considered error-prone.

Key Talking Points:

  • Error Prevention: Catches common coding mistakes that might otherwise go unnoticed.
  • Strict Parsing: Enforces stricter parsing and error handling on your JavaScript code.
  • Enhanced Security: Prevents the use of potentially dangerous features.
  • Backward Compatibility: Can be applied to individual functions or entire scripts.

NOTES:

Reference Table:

Featureuse strict ModeNon-Strict Mode
Variable DeclarationThrows error for undeclared varsAllows undeclared vars
this in Functionsundefined in global functionsGlobal object in global functions
Duplicate Parameter NamesThrows errorAllows duplicate names
Octal SyntaxThrows error for octal syntaxAllows octal syntax

Follow-Up Questions and Answers:

  1. Why should we use use strict in our code?

    • Answer: Using use strict helps maintain cleaner and more secure code. It forces you to follow best practices, reduces the chances of bugs, and provides better optimization opportunities during the JavaScript engine's execution.
  2. How can you apply use strict to a specific function instead of the whole script?

    • Answer: You can enable use strict mode for a specific function by placing the directive "use strict"; at the beginning of the function body. This confines strict mode to that function.
  3. Can you provide an example where use strict would prevent a bug?

    • Answer: Consider the following code snippet:
   // Without 'use strict'
   function myFunction() {
       x = 10; // This creates a global variable unintentionally
       return x;
   }

   // With 'use strict'
   function myFunction() {
       "use strict";
       x = 10; // Error: x is not defined
       return x;
   }

In the second function, use strict prevents the accidental creation of a global variable x by throwing an error, prompting the developer to define x properly.

Want all 100 questions?
Get the full book on Amazon — paperback, Kindle, or hardcover.