Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSarah Saad
Courses Plus Student 3,223 Points'Strict Mode' catches the mistyped variable names in an assignment. How does the JavaScript Engine works it out?
As explained here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode
First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript).
2 Answers
Steven Parker
231,846 PointsIt doesn't actually detect that you mistyped anything. It just does not allow a variable to be created implicitly.
jsdevtom
16,963 PointsI'll start off by saying that I am no expert. Therefore, I'll include how I found this information so that you can see if I made any mistakes along the way.
After some googling, I found out that javascript engines have a parser¹. This guide to Javascript engines is pretty informative as well. Then I went to the v8 engine's repo on github. I then went to have a look at the parser.cc file where I found this section on checking if the code is in use strict mode.
I don't think you have to understand c++ to understand what is going on here. The code checks if there is a directive
if (directive_prologue) {
After which it checks if the 'use strict'; statement is there:
// Check "use strict" directive (ES5 14.1), "use asm" directive.
bool use_strict_found =
If use_strict_found
(and some other weird condition) evaluates as true , it changes the language mode:
RaiseLanguageMode(STRICT);
EDIT: Oh, I read the question wrongly. I don't know. I do know that after the parser has determined that you are using strict mode, the parser sets a different set of semantics from the normal code². AKA, ( I guess ) it will do something to this 'When var is declared, check it has a var sign in front of it. False?: Check if it is declared in a higher scope. False: check if strict mode is enabled. If it is, throw error. Again this is just speculation. I couldn't the relevant section of the code down.
"Strict mode isn't just a subset: it intentionally has different semantics from normal code." Source: Mozilla's strict mode reference