DEV Community

Cover image for "use strict" in javascript
sakethk
sakethk

Posted on

"use strict" in javascript

Javascript is crazy language it will allow us to write bad code that we shouldn't do.

use strict directive introduced in ECMAScript version 5. It is to indicate that the code should be executed in "strict mode".

This directive will tell to interpreter to turn badly written JavaScript into errors for example.

x = 200
console.log(x) // 200
Enter fullscreen mode Exit fullscreen mode

Here above snippet is a not a valid JS code because we haven't declared x variable with let, var or const so with the help of use strict we can solve this problem.

"use strict"
x = 200
console.log(x) // ReferenceError: x is not defined
Enter fullscreen mode Exit fullscreen mode

Also helps to ?

This forces developers to write cleaner, more organized, and more readable code in the process. In fact, use strict is used by many famous JavaScript libraries such as ReactJS, jQuery, and more.

What Exactly use strict will do

Here are the some main features that strict mode includes
  • Forces proper declaration of variables.
x = 200
Enter fullscreen mode Exit fullscreen mode
  • Prevents global variables.
  • Blocks assignment to non-writable global variables.
NaN = 1
Enter fullscreen mode Exit fullscreen mode
  • Blocks repeated object property names.
const x = {a: 1, b: 2, a: 3}
Enter fullscreen mode Exit fullscreen mode
  • Prevents variable/object hoisting.

Strict mode is enabled by default for Ecmascript Modules. Projects built with Babel/Typescript doesn't require it.

Here in MDN Web Docs Page one can read more about the exact functionality of use strict.

Thanks 🙏 for reading.
Hope you enjoyed it.

Top comments (0)