if (true) { var foo = 'bar'; } console.log(foo); // returns 'bar'
(function () { var foo = 'bar'; }()); console.log(foo); // returns undefined
for (var i = 0; i < 10; ++i) { console.log(i); } for (var i; i < 10; ++i) { // this will never get called!! By the // time the code gets here, i is set to 10 }
var counter = (function () { var count = 0; return { increment: function () { count++; }, getCount: function () { return count; } }; }()); counter.increment(); // increments the count counter.getCount(); // returns 1
for (var i = 0; i < 10; ++i) { var b = i * 3; console.log(b); }
var i = undefined; var b = undefined; for (i = 0; i < 10; ++i) { b = i * 3; console.log(b); }
console.log(foo); // returns undefined! // do something var foo = 'baz';
var foo = undefined; // foo is hoisted, it's value is not console.log(foo); // do something foo = 'baz'; // foo doesn't get initialized til here
var foo = function () { console.log(bar); }; var bar = "hey world"; foo(); // displays 'hey world'
var foo = undefined; var bar = undefined; foo = function () { console.log(bar); }; bar = "hey world"; foo(); // displays 'hey world'
var foo = "bar"; (function () { console.log(foo); // prints undefined? var foo = "baz"; // scoped variable that hides the other foo console.log(foo); // prints baz }());
var foo = undefined; foo = "bar"; (function () { var foo = undefined; console.log(foo); // prints undefined? foo = "baz"; // scoped variable that hides the other foo console.log(foo); // prints baz }());
foo(); bar(); function foo() { // bad way console.log('foo called'); }; var bar = function () { // good way console.log('bar called'); }; // outputs: foo called // Type Error!!
function foo() { console.log('foo called'); }; var bar = undefined; foo(); bar(); bar = function () { console.log('bar called'); };
Tom Valletta has a great presentation about this. I highly recommend reading through it.
This will trip you up. A Lot. Unless you learn to get it down right now and practice it tons. This changes based on how the function was called.
console.log(this); // this is the global window object
var foo = function () { console.log(this); } foo(); // this is the global window object var myObj = { foo: foo }; myObj.foo(); // this is myObj
var foo = function (a, b) { console.log((a + b) + " " + this); } foo.apply(Window, [1, 2]); foo.call(Window, {'0': 1, '1': 2}); // output for both of these is '3 Window' // this is only because I passed Window in as the context
var Person = function (name) { this.name = name; return this; }; var fred = new Person('fred'); // this references fred
var myObj = { age: 21, getAge: function () { return this.age; } }; myObj.getAge(); // returns 21; var functionCaller = function (func) { func(); }; functionCaller(myObj.getAge); // returns undefined
Thanks for watching!