JavaScript 101: Scope and Closures

javascript-logo

This article is part of the JavaScript 101 series, you can find the previous part on the following link: JavaScript 101: Functions.

Scope in JavaScript

In programming, the scope refers to the visibility of variables and methods from one part on the computer program to another part. In JavaScript programming language there are two types of scopes, global scope and local scope.

Global Scope is the JavaScript document itself or in other words, when we are outside of functions. We can access or call variables from the global scope inside of our functions. Global scope exists as long as your application is running.

Local Scope is the scope inside a function itself or when a variable is defined inside a function. This means that we can't access or call these variables from outside of the same function or from the JavaScript document itself. Local scope exists as long as your functions are called and executed.

What about block statements like if and switch conditions or for and while loops? unlike functions, block statements don't create a new scope, everything that was defined inside of a block statement will inherit the scope they are. With the introduction of ECMAScript 6 we can use let and const keywords instead of var for declaring variables, which are block-scoped and cannot be accessed or called from outside a block scope.

Closures

In JavaScript closure is the combination of functions, a closure gives you access to the outer scope from an inner function. Let's see a simple closure example in JavaScript.

function nameFunc() {
  var name = 'MyName';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = nameFunc();
myFunc();

First we are calling myFunc which has the nameFunc() inside with the local variable name, and function displayName() as inner function. The displayName() has no local variables but has access to its outer function and the variable name The displayName() is returned from the outer function before executed. When we run the above code the alert will be displayed with the name variable.

Next part: JavaScript 101: Object Oriented Programming.




#javascript #javascript101

Author: Aleksandar Vasilevski |

Loading...