Javascript

Scope & Closure

Contents

  • Scope
  • Lexical scope
  • Function vs Block scope
  • Hoisting
  • Closure

Scope

rules for variable look-up

Errors

Failed variable look-up => ReferenceError

Lexical scope

  • lexical: relating to the vocabulary
  • scope defined by author-time decision
  • not dynamic (except eval & with)
  • Do not use eval and with

Function scope

Block scope

function haveScope (x) {
  console.log(x)
}
{
   // belongs to upper/global scope
   var a = 'variable'
}

for (var i = 0; i < 5; i++) {
  console.log(i)
} 

Block scope with let & const

  • let & const came with ES6
  • Disables hoisting
  • Good for garbage collection
{
  console.log(a); // ReferenceError
  console.log(b); // ReferenceError
  let a = 5;
  const b = {prop: 'value'};
}

Hoisting

  • Moving variable and function declarations to the top of the scope
// 1 and 2 have same effect

/* 1 */
var a;
console.log(a);
a= 2;

/* 2 */
console.log(b);
var b = 3; 


Closures

  • Open access to scope for later use
  • Closures are already exist, you should learn to see
  • Provides keeping variables private
function addNumber(num) {
    return function(anotherNum) {
        return num + anotherNum;
    }
}

var addTwo = addNumber(2);
addTwo(3) // remembers num as 2 and returns 3

Javascript - Scope & Closure

By Özgün Bal

Javascript - Scope & Closure

  • 80