var, let and const in detail with scope

Photo by chuttersnap

Join with me on learning about old var and ES6 let const keywords in Javascript. This topic is splitted into 2 parts (Scope and Hoisting).

Till 2015 var was the only keyword to declare a variable in javascript. After the introduction of ES6 in 2015, javascript has got many features added to it and let and const were two amongst them. These three keywords majorly differ in the way they are scoped.

Scope

Scope is a region of a program where variable or function is valid. It is the oxygen of a program and it lives everywhere. The region or zone or block in which a variable or a function is valid is its scope. If a binding is accessible all over the program, then it is globally scoped. If we try to access a variable outside of its scope, the javascript interpreter will throw error.

In javascript we have two types of scope.

  • Function scope
  • Block scope

Function scope

When a function is declared, inside the body of that function a new scope block is created. Variables that are declared inside the new function scope cannot be accessed from its parent scope. However, the variables in their parent scope can be accessed inside the new function scope. The variables declared with var keyword takes function scope.

Function scope variables are accessible only within their nearest function's curly braces ({}).
1var outer = 10
2
3function doSomething() {
4 var inner = 20
5 console.log(inner) // 20
6}
7
8console.log(inner) // Rerference error

In the above snippet, the variable outer is globally scoped and it can be accessed anywhere in the program. Whereas variable inner is declared inside a function and hence it takes the scope of its parent function (nearest function). As inner variable cannot be accessed outside of its scope where its existence is unknown, this snippet will throw ReferenceError at line 8.

Block scope

A new block scope is created when we introduce curly ({}) braces in our code. This curly braces can be anywhere in the code with keyword words (like if, for) or stand alone, a block scope is created. In javascript let and const are block scoped.

1{
2 let isSignedIn = false
3}
4console.log(isSignedIn) // ReferenceError

In the above snippet, a block scope is created between lines 1 and 3, and so the lifetime of isSignedIn variable is wintin this block.

Take aways

  • Scope is a region of a program where variable or function is valid.
  • Javascript have function and block scope
  • var variables and functions have function scope.let and const variables have block scope.
05/11/2020
All posts
Built with ❤️ and  Gatsby