Block Scope

Kevin Neyer
2 min readJan 8, 2021

Declaring Variables Successfully

Photo by Joshua Reddekopp on Unsplash

Introduction

When working in JavaScript, we, as developers, have to deal with a concept called scope. Simply put, scope is where something lives, and defines where within the context of our code it can be accessed. While there are different types of scope — global, function, lexical, to name a few — I want to talk about block scope.

Block Scope

When a variable is placed within curly brackets {}, as used in an if statement, and if…else statements, it falls into consideration for block scope. Where this becomes important is in how we declare variables. There are three ways to declare variables: var, let, and const. let and const are block scoped, whereas var is not. What does this mean? It means that, if you declare let or const within curly brackets, then it is only accessible inside the curly brackets. Let’s take a look!

While this may seem quite logical, block scope is something to consider when declaring variables. Plus, it’s a nice little spice to add on to an answer to the common question, “What’s the difference between var, let, and const?

Summary

In the world of our code, we can put things wherever we want. It is important, however, to see how the arrangement or living spaces of our code(variables, functions, things that may get called upon later) play into the bigger picture. Thinking about scope will help solidify that our code executes and returns the values we set out to achieve. As always, don’t forget to look at the docs and try it for yourself. Happy Coding!

--

--