8

Strict mode in JavaScript

 2 years ago
source link: https://dev.to/abhishek_rath/strict-mode-in-javascript-cl7
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

What is strict mode?

  • Strict mode was introduced in ECMAScript5 also known as ES5 in 2009.
  • Adding strict mode to JavaScript code allows your code to be checked more strictly.
  • Allows programmer to write more secure JavaScript code.

Benefits of Strict Mode

  • Using strict mode in JavaScript code throws visible errors in developer console which would otherwise fail silently (shown in the examples below).
  • Forbids programmers to use certain syntax.
  • In some cases using strict mode in code can make the code to run faster.

How to enable strict mode in JavaScript?

  • To enable strict mode write "use strict" or 'use strict' at the beginning of JavaScript code.

  • The strict mode can also be used for a function.

  • To enable strict mode in function, "use strict" or 'use strict' must be the very first line in function body.

Common mistakes that occur in non-strict mode

Using reserved words as variable names

  • Wait!! Isn't "let" a reserved word in the JavaScript? Therefore it mustn't be used as a variable name according to naming an identifier rules. Here in the above code snippet JavaScript fails silently instead of throwing an error.
  • But, if we use strict mode, JavaScript engine will throw an error- Strict mode in code snippetProduces error

Using variables before declaring them

  • Using strict mode gives Reference Error.

  • To know more about the strict mode, checkout the documentation by MDN

Conclusion

  • That will be all from my side. I hope, this article gave you a basic idea about the strict mode.

Keep Learning!!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK