What does “use strict” do in JavaScript, and what is the reasoning behind it ?

What does "use strict" do in JavaScript, and what is the reasoning behind it ?
What does “use strict” do in JavaScript, and what is the reasoning behind it?

“use strict” is a directive in JavaScript that tells the browser to run the JavaScript code in “strict mode.” Strict mode is a way to opt in to a restricted variant of JavaScript that is more efficient and has better error-checking.

When you use “use strict” at the beginning of a JavaScript file or a function, it changes the behavior of certain constructs to help you write more robust code. Here are some of the changes that happen when you use strict mode:

  • Variables declared using var keyword must be initialized before use
  • It eliminates some JavaScript silent errors by changing them to throw errors
  • It makes this keyword behave differently in certain situations
  • It prohibits the use of certain unadvisable and/or deprecated syntax

Here’s an example of how you can use “use strict” at the beginning of a JavaScript file:

"use strict";
x = 5; // this will cause an error, because x is not declared

The reasoning behind strict mode is that it makes it easier to write more secure, reliable, and maintainable JavaScript code by catching errors that might otherwise go unnoticed. It makes sure that you’re not relying on any of the old, bad parts of the language and it helps you avoid common pitfalls that can cause unexpected behavior or performance issues.

It is highly recommended to use strict mode, as it makes your code more robust by eliminating some silent errors and can help you identify bugs early in development. It’s also a good way to make sure that your code is not relying on old, deprecated features of the language.

It’s worth noting that strict mode only applies to the code in which it is used. It does not affect the code in any other scripts or in any code that is executed after the current script.

Leave a Reply