Scopes & Closures in JavaScript

Himesh Vats
2 min readJun 25, 2019

Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.

#Global Scope

If a variable is declared outside all functions or curly braces ({}), it is said to be defined in the global scope.

Although you can declare variables in the global scope, it is advised not to. This is because there is a chance of naming collisions, where two or more variables are named the same.

#Local Scope

Variables that are usable only in a specific part of your code are considered to be in a local scope. These variables are also called local variables.

n JavaScript, there are two kinds of local scope: function scope and block scope.

## Function Scope

When you declare a variable in a function, you can access this variable only within the function. You can’t get this variable once you get out of it.

## Block Scope

When you declare a variable with const or let within a curly brace ({}), you can access this variable only within that curly brace.

In General Scopes

Let’s run through this

& this

finally, this…famous counter problem

--

--