00:33 This will result in a parsing error. That’s because the parser doesn’t pay any attention to newlines. It sees that code snippet as this. You can’t name a function with a number, so you get an error. To get this to work as expected, you want to be explicit about your semi-colon.
This quirk can be even trickier. You could conceive of a weird edge case where instead of adding
3, you are adding a variable. The same thing would happen, but you wouldn’t get an obvious parsing error. You’d get a
RuntimeError when it tried to call your variable as a function.
for loop structure.
The three parts of it indicate an initializer that is run before the loop, a comparator that if
True allows the next iteration of the loop to run, and the third section, run before entering the next iteration of a loop, typically used to increment your counter.
As I point out before, you can’t use this with an array. This also has the confounding feature that it includes things attached to the prototype. So if you’ve got a richer object, rather than just a vanilla dictionary-like thing, you may get more than you expect. The attributes returned by the
in keyword have a method called
hasOwnProperty(), which will return
True if the attribute belongs to the object instance. To safely use
in together, you should check that the attribute belongs to the instance of the object.
03:46 There’s some clever tricks you can use to check whether this is happening inside the constructor function to prevent this problem, but I prefer to just stick with ES6 classes. You’ll get an error if you make this mistake with a class.
It is important to note that it doesn’t matter where in the function it is declared. It is visible to the whole function. Declaring a variable inside code blocks like
if statements or loops doesn’t hide the variable from the function.
How’d you do? Don’t worry if you didn’t get it. Something a bit strange is going on here. It is called variable hoisting. The declaration of
var x in the function causes the namespace override for the whole function even before the line where it is declared.
This means you can call a function before it appears in the code. Be careful, though. If you use
var to define a reference to a function expression, it will get hoisted and the variable definition will exist before the function expression assignment, and you’re back to having a problem.
Become a Member to join the conversation.