Block, Function, and Global Scope in JavaScript

Emma Lowe
The Startup
Published in
2 min readJun 4, 2020

Understanding the basics of how scope works in JavaScript will save you future headaches, time, and bugs.

Photo Credits: Vlada Karpovich, Pexels.com

Lets talk about variable declarations. Var, let, and const. What’s the difference? If you are treating these like Chickpeas and Garbanzo beans, then it’s time to change your ways. Let’s walk through the differences together.

Var and Let

Before ES6, JavaScript only had function and global scope. This meant that a variable declared inside a function lived inside the function and a variable declared outside a function could live anywhere. This means that variables declared inside if statements or other code blocks are globally scoped and live outside their code block. Like so:

As you can imagine, this has the potential to cause issues in our projects.

With ES6, JavaScript introduced the let keyword and block scope. Block scope means that if a variable is declared using let or const in a code block it lives only in that code block. This changes our example to look like this:

On line 20 a new variable also named dog is being declared and initialized, but it dies as soon as the if statement is exited. On line 24, the console log is referring to the first dog variable declared and initialized on line 16. Thus, Fido not Argo is returned.

Here is a more simple snippet illustrating the the scopes of var, let, and const side by side.

Tip: If you have trouble keeping let and var strait, remember these phrases: “var goes far” and “let me out”.

Summary:

Let

  • Block scoped

Const

  • Block scoped

Var

  • Function scoped

If you enjoyed this article, give it a clap and checkout my article on understanding hoisting in JavaScript to deepen your understanding of JavaScript scope.

--

--

Emma Lowe
The Startup

Emma is a software dev who synthesizes information best through writing. She believes clear documentation and communication go hand in hand with good code.