Function Scope vs Block Scope in JavaScript

Hi there!

When I first started coding, I had trouble understanding the difference between function scope and block scope. Therefore, I took short useful notes for myself, and now I want to share them with you. I hope you will find answers to your question marks about this subject after reading my article.

Let’s start!

While coding, you make use of somethings like variables, objects, and functions and call them in certain places in the code. These variables or objects in the code have a scope of necessity, which is called scope. There are two fundamental types of scope in Javascript.

  • Global Scope
  • Local Scope

What is the Global Scope?

It is a scope type defined outside the functions within the program and accessible from anywhere. A variable defined in the Global Scope can be accessed from anywhere within the file. Shortly, you can say that global variables have a global scope.

Using it isn’t recommended. As, local variables are deleted from memory after done, while global variables remain. This situation may cause some memory problems in the future. Therefore, many people don’t prefer using global variables.

What is the Local Scope

Unlike global variables, local variables are only available inside of the function or block scopes like if statement or loops.

(If you don’t know the block scope, don’t worry about it because I will explain in the other part.)

In the screenshot below, you can see both Global and Local scope examples. The variable inside the function is a local variable(var localVar=3)and it can’t be reached from outside.

What Happens If You Try To Access The Local Variable Outside The Function?

We receive ReferenceError because local variables could not be accessed from outside the function.

However, the scope of the variables changes according to the keyword you use. When you use var, it is function scope while if you use let or const, it is block scope based.

What is the Block Scope?

Block Scope is a declaring a variable inside curly brackets { } like in an if statement or for loop.

Let’s look at the example below. We created an if statement and defined a new variable with var and the result proceeded like the examples above.

In shortly, var is a function scope based which is valid in the defined function. Variables in if or loop don’t create a new scope. They are accessible everywhere with the function are defined.

In addition to var, there are let and const too. let is block scope based. The value of const never changes and cannot be used with the same name again.