What You Need To Know About Scope in JavaScript - No Buzzwords

What You Need To Know About Scope in JavaScript - No Buzzwords

Scope explained for JavaScript beginners

What is Scope in JavaScript?

A brief about JavaScript Variables.

We declare variables in every JavaScript file and we want to use those variables in our codebase.

When we declare a variable in a function, it's scope is only limited to the function.

I wrote about JavaScript Variables and the difference between naming and declaring variables, you can read about it below.

JavaScript Keywords and Variables Definition - Explained For Newbies

Let's talk about Scope.

According to the English dictionary, scope is the breadth, depth or reach of a subject; a domain.


In programming generally, scope is that region in our code in which a given identifier can be used.

When we declare a variable in a function, we can only use the variable in the function, which means that it's scope is only limited to the function.

Let's break it down.

JavaScript has 3 types of scope:

• Block scope

• Function scope

• Global scope

Defining each type

1. Block Scope

Look at a block in JavaScript like codes in a curly bracket.

{ code }

In the image below, the "let" keyword makes it's variable used only in the scope.

x = undefined outside the scope.


The "var" is more flexible.

Outside the scope, x is defined.


2. Function Scope

A variable declared by "let" keyword can only be used in the scope of the function.

carName variable is undefined outside the function.


We can have variables with same names but in different functions.

For example,


3. Global Scope

Variables declared outside a function or curly brackets becomes a global variable.

All scripts and functions on a web page can use the global variables in the page.

Note that "carName" was not declared in a function or curly brackets.


Function variables are deleted when the function is completed.

Global variables are deleted when you close the browser tab.

Resources to learn more about Scope in JavaScript:





End of blog.

Hopefully you'll find this blog helpful as you learn to code more effectively, and to know that there's a lot more to coding than write codes.

Before You Leave,

If you enjoyed this article and want to see more content related to JavaScript and web development, then follow me here, Twitter and connect on LinkedIn.

I'd be happy to count you as one of my ever-growing group of awesome friends on the internet, don't forget to react to the blog.

Hit some icons!! 💕

Credits: Some screenshots are taken from w3schools.