An intro to Scope according to JavaScript

Lets talk about scope for a minute…

Scope can be referred to as the ruleset used to look up variable values. Javascript has two main ways to create new scope, function scope with the var keyword as well as block scope with the ES6 let keyword.

Function Scope

A new scope can be created by declaring a function. Outside the function is the global scope, a variable defined in the global scope can be accessed by any script or function. Inside a function is a scope local to that particular function. Lets look at some code.

The first foo is in the global scope. If we log foo out to the console it will give us the string ‘cat’.

console.log(foo); => cat

The second foo is local to the scope of the function bar. If we invoke bar we get the string ‘dog’.

bar(); => dog;

Yes this is an extremely simple example, but we can see that a new scope was created when we declared the function bar.

Block scope with let

With the addition of let and const in ES6 we can now create a block scoped variable reference. Anytime there are a set of { } and a let keyword, new scope is created. Here is a simple example showing what happens when we use the var keyword

We can see that when we invoke foo(); bar will set to ‘dog’ because a new scope is not created and bar is reassigned.

If we change the vars to lets and run this code again, it will print dog, cat to the console. Our let declaration created a new scope between the curly brackets of this pretty useless if statement.

Things to consider…

Passed parameters

When a function calls for one or more parameters, the arguments passed in are implicitly declared and then locally scoped to that particular function.

The first bar is global, and the second is a passed parameter which has a scope local to the function foo. We could also call this function with a passed argument, such as ‘cat’ and get the same result.

Scope Chain Look-Up

Functions have access to their outer context. For example a function declared in the the global scope has access to the variables declared there. A function declared inside of another function has access to the global scope, as well as, any variables declared in its parent function.

Study this code and pay attention to how function two has access to variables declared in function one. When function one tries to reference a variable declared in function two, a reference error is thrown.

To quickly recap, in JavaScript new scope can be created globally, with functions, and using the let keyword between some curly brackets. Thanks for reading, I hope scope got just a little clearer!


One clap, two clap, three clap, forty?

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