Javascript Scope & Closure

Objectives

  • Explain what scope is
  • Compare global and local scope
  • Define closure and its use cases

What is scope?

  • Scope is the set of variables, objects, and functions you have access to
  • Has two types of scope: Global and local
  • Global scope: variables declared outside of functions
  • Local scope: variables inside functions

What is scope?

Closure

var foo = function(name) {

  var bar = function() {
    console.log(name);
  };

  return bar;
};

var a = foo('matt');
a();

var b = foo('mark');
b();

Scope

// Example 1

var a = 10;

var foo = function() {
  a = 20;
  console.log(a);
};

console.log(a);


// Example 2

var a = 10;

var foo = function() {
  var a = 20;
  console.log(a);
};

console.log(a);
// Example 3

var a = 10;

var foo = function() {
  var b = 20;
};

console.log(b);

What is closure?

  • An inner function that has access to the outer (enclosing) function's variables

Think Pair Share

  • List some use cases or examples of closures

deck

By Matthew Gutierrez