Understanding variable declaration and scope in JavaScript!!

Understanding variable declaration and scope in JavaScript!!

In JavaScript, the variables are declared using var, let, and const keywords. Let's understand how each of these keywords varies from each other.

ยท

5 min read

While using JavaScript we use var, let, and const to declare a variable.

But without knowing where to use which keyword would make us go through a lot of trouble but worry not by the end of this blog you would be able to choose which keyword is required where.

Factors influencing variable declarations

  • Scope
  • Reassignments
  • Accessing a variable without declaring

Now, let's understand each factor and how it affects the variable declaration.

Scope

In JavaScript, the scope is a way to identify if a variable is existing to use ie whenever we are trying to use a variable whether we can use that variable at that particular point of time or not.

There are three types of scopes in which a variable may exist:

  1. Block Scope
  2. Function Scope
  3. Global Scope

Block Scope

Let us understand what a block is first.

{ 

//anything inside these curly braces is considered to be in block scope

}

Rules of usage of Block scope:

  1. If you do not want a variable declared inside a block to be accessible outside the block then you use let and const to declare the variable.

  2. Any variable declared inside the block using the var keyword is still accessible outside globally.

{

let name = 'Jon';             //not accessible outside block
const age = '25';            //not accessible outside block
var city = ' New York'       //still accessible outside block

}

console.log( name)         //throws Reference error 
console.log(age)           //throws Reference error 
console.log(city)         //New York

Function Scope

Function scope is anything that is inside of a function is called function scope.

Rules of usage of Function scope:

  • A variable declared inside a function using keyword (var,let,const) are not accessible at all outside the function scope
function getDetails( ) {

      let name = 'Jon';             //not accessible outside block
      const age = '25';             //not accessible outside block
      var city = ' New York'        //not accessible outside block

}

getDetails();

console.log(name);        
console.log(age);
console.log(city)

//each console.log() results in error.

Global Scope

  • Anything outside of the block or function scope is in the global scope.

let name = 'Jon';             
const age = '25';             
var city = ' New York'

function getDetails( ) {

console.log(name);          //Jon    accessible if function scope because they are globally declared
console.log(age);          //25
console.log(city)          //New York

}
  • In the global scope, we can use var to declare variables. However, we should not declare globally with the var keyword. When we do so there are higher chances of overriding the values.

  • We should try to scope variables close to their usage.

Reassignments

If we have a variable that has been declared using the keywords and has been initialized with some value then when we try to re-assign that variable with some value. The re-assign behavior will depend on what keyword we have used to initialize the variable.

let name = 'Jon';             
const age = '25';             
var city = ' New York'

//above we have let, var, const keywords assigned with some values

//when we try to re-assign

name = 'Chris';             
age = '20';                 //Error : Assignment to constant variable
city = 'Chicago'
  • We can re-assign the value of a variable if it is declared using the let and var keywords.

  • We cannot re-assign the value of a variable declared using the const keyword.

But here is the tricky part that JavaScript throws at us:

  • If we declare a variable with const and assign it with value as an object, then we will be able to change the value of the object's properties but we will not be able to assign it to a new object.
const obj = {

  name : "Bryan",
  city: "Las Vegas"

}

obj.name = 'Tristy'   //Allowed to change objects property values

obj = {           
                                 //Not allowed
  name: 'Ron',
  city: 'Washington'

}

Accessing a variable before we declare it

  • When we are trying to access a variable before it is declared in non-strict mode.

๐Ÿ“Œ If it is declared with var then we will get undefined.

๐Ÿ“Œ If it is declared with let and const then we will get a Reference error.

console.log(pat)   //ReferenceError: pat is not defined

let name = 'Pat'

console.log(date);   //undefined

var date = '25th'

Reasons for the different outputs above.

  • For var keyword, when declared it is hoisted on top of the window object and initialized with undefined value and accessible before initialization.
  • For let and const, they are hoisted but they are hoisted in different spaces than var and are inaccessible before initialization.

Hoisting: The ability to access variables and functions even before declaring/giving some value to it, without getting an error.

Also, let's understand one more important thing that can confuse you during interviews.

{

var a = 10;
var a = 20;      //re-declaring a and now value of 20

}
{

let a = 10;   
let a = 20;     //SyntaxError: Identifier 'a' has already been declared

}
  • It's permissible in JavaScript to declare the same variable twice in the same scope with var.

  • However, for let and const JavaScript doesn't allow redeclarations in the same scope

Conclusion

  • We covered how variable declarations are affected by scope, reassignments, and accessing them before they are initialized.

  • We also understood that var can create problems when it is used, hence we should avoid using var.

  • We should use let and const more.

  • If we need to re-assign the value to the variable use let otherwise go with const.

  • Also, not to access a variable without declaring it.

I hope you liked this blog and understood var, let, and const in JavaScript

Follow me on Twitter, LinkedIn

ย