JavaScript

Scopes


Will Klein

JavaScript Looks Like...


JS looks like C

C has block-level scoping

JS has function-level scoping

JS is not C

Function-level Scoping

var f = function() {    var a = 1;    if (true) {        var a = 2;    }    return a; // 2};
a is scoped to its parent scope, function f

if, for, while, etc. blocks don't get their own scope

Hoisting

var g = function() {
    b = 1;
    var b = b + 2;
return b; // 3 };
b is scoped to its parent function g

The above is equivalent to:
var g = function() {    var b;
    b = 1;
    b = b + 2;
return b; // 3 };

Globals

var g1 = 'g1 is a global';g2 = 'g2 is a global';
(function() { var l = 'This is local'; g3 = 'g3 is also a global';})();
Missing a var creates a global!

Don't mind the IIFE:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Reusing the Same Variable Name

var a = 1; // a: 1
(function() {
    var a = 2 // a: 2
    (function() {
        var a = 3; // a: 3
    })();        (function(a) {        // a: 4    })(4);
})();
// a: 1
a exists uniquely in each scope

Closures

(function() {
    var a = 1;

    (function() {
        a++;
    })();
    // a: 2
})();
This is a basic closure

Applying Closures

var count = (function() {
    var count = 0;

    return function() {
        count = count + 1;
        return count;
    };
})();
count(); // 1
count(); // 2
A more useful closure

Thanks!


@willslab

http://willkle.in

github.com/willklein
Made with Slides.com