Variable Declarations in JavaScript

Harshit Bansal's photo
·

6 min read

Variable Declarations in JavaScript

In JavaScript, variables can be declared in 3 different types, which are var, let and const. We have already covered var declarations, now we’ll be covering the remaining two.

NOTE: Let & Const declarations are also hoisted but they are hoisted differently than var.

Let’s start with a code in which there are two variables one of which is let and other is var declared.

console.log(b)
console.log(a)

let a = 10
var b = 20

So when this code will be executed, then the engine will allocate memory to both the variables in the memory allocation phase but in the code execution phase, it will throw an error.

The value of b has been printed as undefined but in the case of a it gives us an error and it says that cannot access a before initialization. This error tells us that you can only access this a after you have assigned or initialized some value to it.

Let us see inside the browser and see in detail what happened behind the scenes. Was this variable a located memory or not?

We can see that both the variables have been allocated memory but there is a difference. Variable b is stored inside that global object i.e. window object with undefined value but the variable a is stored inside some Script object which is outside the global object and it is showing value unavailable.

This happened because, in the case of let and const, they are allocated memory which is known as Hoisting but unlike var, they are stored in a separate space other than global space and that space cannot be accessed. That’s why let & const variables cannot be accessed before initialization.

Temporal Dead Zone

Temporal Dead Zone is a time since when these let & const variables are hoisted, until they are initialized with some value. Like in the code above, a was hoisted in the starting of the program itself but it got initialized at line 4, therefore the time between that is temporal dead zone and if you’ll try to access it inside the temporal dead zone, it’ll give you a Reference Error.

Also we cannot access the let & const variables using window or this keyword as well unlike var.

This strictness is added for security reasons, there is one more strictness in the case of let variables that they cannot be redeclared. In the above code, a has already been declared so you cannot redeclare it.

But it can be initialized again with some other value. As here we are changing the value of a from 10 to 20, it will be done successfully.

Redeclaration of a let variable is a Syntax Error which means that no other code will be executed, if we try to put a console.log before redeclaring it, it’ll throw the error without printing it.

let a = 10;
console.log(a)

let a = 20;
console.log(a)

This happens because the engine throws this error in the memory allocation phase only before even going to code execution phase.

Const variables are even more restricted than the Let variables as they cannot be even initialized again. They have to be initialized during declaration only, they cannot be initialized later as they are constant variables and can be initialized only once.

When we are trying declare c without initializing it then it gives SyntaxError, but if we are trying to change the value of c, it is giving us a TypeError and earlier we got a ReferenceError.

What is the difference between these types of errors

  1. SyntaxError: This occurs when there is a mistake in the syntax of the code, making it impossible to parse. For example, missing brackets or incorrect use of reserved keywords can lead to a SyntaxError.

  2. ReferenceError: This happens when you try to access a variable that hasn't been declared. It indicates that the code is referencing something that is not available in the current scope.

  3. TypeError: This error is thrown when an operation is performed on a value of the wrong type. For instance, trying to call a non-function as if it were a function, or accessing a property of undefined or null or changing the value of a const variable.

Ways to avoid errors while declaring variables

  • Use const variable declarations whenever you can and if not const then let, but do not use var declarations (for security concerns).

  • Always try to declare your variable in the start of the program to avoid any un-necessary errors.


Blocks in Javascript

A block is a group of multiple lines of code bound together to act as a single line of code. There are many places in a program where we can use only one line of code, so there blocks are used to represent multiple lines as a single line. Like, conditional statements and loops.

Any code between {} is said to be a block and an empty block is also a valid block.

{
// Your Code
}

What is Block Scope ?

Block Scope means what all variables and functions we can access inside this block. Let us understand with the help of an example.

let a = 10;
{
    let a = 20;
    let b = 30;
    let c = 40;

    console.log(a);
    console.log(b);
    console.log(c);
}
console.log(a);
console.log(b);
console.log(c);

In the above code, we have created a variable an outside the block in the global space and other 3 variables inside the block. Let ‘s have a look at the output of the above code.

As we can see, the logs inside the block worked as expected but the logs outside the block worked differently. The console.log(a) inside the block printed 20 which was the value of an inside block and the console.log(a) outside the block printed 10 as a was 10 in the global space. Rest b and c were not declared outside the block that’s why they gave a ReferenceError. Hence, we know that let is block scoped. Const is also block scoped.

Let’s have a look at this code where variables are var declared instead of let.

var a = 10;
{
    var a = 20;
    var b = 30;
    var c = 40;

    console.log(a);
    console.log(b);
    console.log(c);
}
console.log(a);
console.log(b);
console.log(c);

The output of this code will be different.

This is because var is not block scoped and can be accessed from anywhere. Also, we can see that the an inside the block replaced the value of an outside the block. This happened because var declarations are stored inside the global window object and has only single reference.

Shadowing

When a variable inside a block gives its value instead of a variable with same name outside the block, then it is said that the variable inside the block has shadowed the variable outside it.

Shadowing is said to be done when a variable inside a block overlaps the value of a variable with same name outside the block.

In the case of both variables as let or const shadowing happens, and in the case of var it updates the value in global object.

NOTE → It is possible that the block variable is let or const and the outer variable is var but the vice-versa is not true as var tries to access the global object only.

let a = 10
{
    var a = 20;
    console.log(a)
}

It throws a SyntaxError as here it will be considered as re-declaration of a.