Types of errors that strict mode catches (that would otherwise be ignored)
Andrew Borstein asked a few follow-up questions to Monday’s article about strict mode over in my Vanilla JS Slack Room.
Yesterday, I clarified where to enable strict mode in your scripts. Today, let’s talk about the kinds of errors it catches.
What’s an example of an error that would be silent without [strict mode]?
Types of errors that would get ignored without strict mode include…
- Calling a variable that hasn’t be explicitly set.
- Redefining a variable that’s already been defined.
For example…
// Undefined variable
var anotherVar = 'another variable'; // No error
anotherVar = 'change variable value'; // No error
aThirdVar = 'a third variable'; // Error. Not yet been defined with `var`
// Previously defined variable
anotherVar = 'change variable value'; // No error. You're changing the value of a previously set variable
var anotherVar = 'change the value again'; // Error. The variable has already been set, so you should leave off the `var`, which implies it's a new variable