A bit of Perspective with JavaScript Scopes

JavaScript Scopes

What are scopes anyway? Scopes are the current context of the code. They are composed of variables, objects, and functions that you have access to, and they can be globally or locally defined.

Global and Local Variable Scopes

You have 2 types of variable scopes — global and local. Your global can be accessed from everywhere and anywhere. For local, that can be accessed within the function’s scope. For a human example, think of local scope as telling a dirty, little secret to your best friend. With sworn secrecy, your BFF doesn’t say a word about your secret to anyone. But with global, think of it as tweeting, updating, messaging, calling, and whatever social media outreach that publicize your secret. Now everyone knows your dirty, little secret!

Two key questions to ask yourself when determining a variable’s scope:

  1. Is it declared inside a function?
  2. Is it declared with the var keyword?
function myFunction(){
y = 2;

If a variable is declared in the outermost scope of a project, outside of any function, then it’s a global variable.

var x = 1;               //I'm a global variable with global scope!
function myFunction(){
y = 2; //I'm a local variable with local scope!
console.log(y); // Error!
console.log(x); // 1

You will get a ReferenceError: y is not define. At this very moment, the y is a global variable that is stored in the function myFunction, but is not defined. You need to invoke the function first, and then the global variable exists.

var x = 1;
function myFunction() {
y = 2;
myFunction(); // 1
console.log(y); // 2 - It works this time!
console.log(x); // 1

Because of myFunction call, the global variable y exists, and console.log(y) will work!

Talk about Closures

JavaScript has first-class functions. They are first-class objects, because they can have properties and methods just like any other object. We can invoke functions, and we can pass them around with ease.

Closures are inner functions that have access to outer, enclosing function’s variables — scope chain. They have 3 scope chains and have access to:

  1. own scope (variables defined between its curly brackets)
  2. outer function’s variables
  3. global variables

A Quick Recap

In a Nutshell

It’s all about perspective, and scopes are just like that. Perspective.

More Readings

Everything you wanted to know about JavaScript Scope

Understand JavaScript Closures with Ease

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.