I have been writing my recent blog posts to reflect the ways in which I am trying to clean up and make my JS code more readable. One of those ways I want to talk about in this blog post is implementing “strict mode” into your code.
“use strict” at the beginning of your code so that it is globally scoped, or you can place it within specific functions or blocks. For simplistic purposes, I like to just put it at the top of my editor in the global scope so that all the code will be in “strict mode” now.
Now you might be asking what would be the purpose of this?
It makes sure that your code is less error-prone. For example, if you try to write a variable without a declaration, it will cause an error:
I think this is an amazing feature from ES5 that is really helpful, especially if you find that you do not have something like ESLint already installed in your editor(if you do, it should still work).
As a result of “strict mode” not allowing for undeclared variables, this also means a by-product is catching misspelled variables.
On line 7 and 8, I misspelled
voting and instead wrote
votin , but since
votin was never declared I automatically get a ReferenceError and it won't run. I will get a message telling me:
If I were to run this code without the ‘use strict’ expression, however, no error would occur:
Strict mode helps us avoid an error like this!
I can never remember, with the exception of the more common keywords, which ones are reserved words. Strict mode will tell you if your variable name is a reserved keyword with an error message.