Activating Strict Mode
Writing this activates strict mode for the entire script. Now it's important to note that the statement
We can also activate strict mode only for a specific function or a specific block. I've tried to understand while some developers do that, but I haven't, so I always use it at the beginning of each script, and I would advise you to do the same.
Let's have an example of one of the most important changes strict mode introduces. Consider the below code example:
//'use strict' let hasBeenAdmitted = false const passInterview = true if (passInterview) hasBeeAdmitted = true if (hasBeenAdmitted ) console.log('Hey! Welcome!');
From the above code, we are just doing a very simple check in which a certain person right now is not yet an employee of a certain company (
hasBeenAdmitted = false ) but has succeeded in an interview (
passInterview = true ). We now check to see if this person has succeeded in the interview; he should be admitted.
You will notice that on the first highlighted line, I introduced a bug. I intentionally omitted the letter
hasBeeAdmitted ). This is to show you how strict mode can help us avoid certain kinds of errors because doing this is more common than you might think.
You can now see that I wrote the variable name correctly in the if condition on the second highlighted line. For the moment, as you can see in the above code, I deactivated strict mode (
// 'use strict' ) so that we can see how this bug can affect our code.
Now, if you run this script by reloading your browser, you will see that nothing has been logged in your console even though we attempted doing this:
hasBeeAdmitted = true. We expected that
true should then log
We are eventually getting nothing, which is normal because of the bug I introduced on purpose by omitting the letter
n. So by correcting that, we will get the expected result.
We get an error! An error saying
hasBeeAdmitted is not defined. That's where we then say, "Oh! I made a mistake! I'm missing an n on my variable name". After correcting that typo, if we try reloading the browser again, we can see that the error is gone.
Another thing that strict mode does is to introduce a shortlist of variable names that are reserved for features that might be added to the language a bit later. For example, let's try to define a variable called
'use strict' const implements = 'something'
If we reload our browser, we see an error saying:
There are many other changes that affect things that we haven't yet learned about, like functions, objects, setting properties, and many more. All these will be mentioned in upcoming lectures.
To finish, in all the upcoming lectures, for all code snippets that will be given as examples, make sure you test them in strict mode to have the same results.