JavaScript Fundamentals 101: Scope and Closures

danvyle

Dan-Vy Le

Posted on January 1, 2020

JavaScript Fundamentals 101: Scope and Closures

Scopes

Scope refers to where variables and functions are accessible, and in what context it is being executed. Basically, a variable or function can be defined in a global or local scope. Variables have so-called function scope, and functions have the same scope as variables.

Global Scope is when a declared variable can be accessible by anywhere inside your code.


var wideReceiver = "DK Metcalf!"; //This variable is available due to global scope
function playerSighting () {
console.log("Look! " + wideReceiver);
}

playerSighting(); //output: "Look! DK Metcalf!"

Local Scope is when a variable is only available inside the function in which it was declared.


function playerSighting () {
var wideReceiver = "DK Metcalf!";
return alert(wideReceiver);
}
alert(wideReceiver); //  ReferenceError: wideReceiver is not defined

//Because its scope is local, it will throw an error

It is also worth noting that nested functions on the same level will also have access to one another, Robert Nyman provides a good example:

function siblings () {
  var siblings = ["John", "Liza", "Peter"];
  function siblingCount () {
    var siblingsLength = siblings.length;
    return siblingsLength;
}
  function joinSiblingNames () {
    return "I have " + siblingCount() + " siblings:\n\n" + siblings.join("\n");
}
  return joinSiblingNames();
}
alert(siblings()); // Outputs "I have 3 siblings: John Liza Peter"

Closures

A closure is the combination of a function and the lexical environment within which that function was declared. In other words, a closure gives you access to an outer functionโ€™s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Consider this example:


function footballPlay() {
  var quarterBack = "Russell Wilson";
    function runPlay() { //runPlay is the function inside the function aka inner function aka closure
      console.log(quarterBack + ", give it to Beast Mode."); // it's using the variable from outside the inner function
    }
    runPlay();
  }


footballPlay(); // output: Russell Wilson, give it to Beast Mode.

Here's another more intricate example given by Mozilla documentation:


function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5); // a closure
var add10 = makeAdder(10); //also a closure

console.log(add5(2));  // 7
console.log(add10(2)); // 12

add5 and add10 are both closures. They provide different lexical environments within the same function. One adds 5 to the makeAdder function, one adds 10 to the makeAdder function.

Hope this helps you understand scopes and closures better, please let me know if you have any comments/additions!

Resources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

https://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
danvyle
Dan-Vy Le

Posted on January 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About