Let var const in Javascript

Let var const are keywords of javascript used to declare variables. let’s discuss them one by one below

Var

Prior to the introduction of ES6, declarations were governed by var. However, there are issues related to variables declared with var. Because of this, it was necessary to develop new ways of declaring variables. Before discussing these issues, let’s first understand var better.

Scope of var

Scope essentially means where these variables are available for use. var declarations have global scope or function/local scope.

The scope is global when a var variable is declared outside of a function. This means that any variable declared with var outside of a function block is available for whole window use.

var is function scoped when declared inside a function. This means that it is available and can only be used within this function.

Let’s understand with an example

var greeting = "Hey Hii";

function fun() {
    var Hello = "hello";
}

Here, the greeting has global scope since it exists outside of a function, while Hello has functional scope. Therefore, we cannot access the Hello variable outside of a function. So if we do:

var greeting = "Hey Hii";

function fun() {
    var Hello = "hello";
}
console.log(Hello); // It will throw an error: Hello is not defined

We get an error because hello is not available outside of the function.

 

Variables declared with var can be redeclared and updated

This means we can do this in the same scope and not get an error message.

var greeting = "Hey, Good Morning!";
var greeting = "Hey, Good Afternoon";

and also

var greeting = "Hey, Good Morning!"
greeting = "Hey, Good Afternoon!"

 

Hoisting of var

Hoisting is a JavaScript mechanism by which variables and function declarations are moved to the top of their scope before code execution. That means when we do this:

// Here we are accessing greeting before its declaration
console.log(greeting);  // It will not throw any error it will print undefined
var greeting = "Hey, Good Morning!";

It is interpreted as:

var greeting;
console.log(greeting); // greeter is undefined
greeting = "Hey, Good Morning!";

Then, var variables are hoisted to the top of their scope and initialized to a value of undefined.

 

Problem with var

There’s a weakness that comes with var. I’ll use the example below to explain:

var greeting = "Hey Hi";
var count = 4;

if (count > 3) {
    var greeting = "Hii how are you"; 
}

console.log(greeting) // "Hii how are you"

Since count> 3 returns true, the greeting is redefined to “Hello, how are you”. While this isn’t a problem if you knowingly want to redefine the greeting, it becomes a problem if you don’t realize that a variable greeting has previously been defined.

If you use the greeting elsewhere Once you have your code, you may be surprised at the output you can get. This will probably cause a lot of errors in your code. For this reason, let and const are needed.

 

Let

let is now preferred for variable declaration. This is not a surprise as it is an improvement over the var. It also solves the var problem we just covered. Let’s consider why that is.

 

Scope of let

A block is a piece of code delimited by {}. A block lives between curly brackets.

Everything between curly braces is a block. Therefore, a variable declared in a block with let is only available for use within that block.

Let me explain this with an example:

let greeting = "Hey, Good Morning";
let count = 7;

if (count > 6) {
     let Hello = "Hello, how are you";
     console.log(Hello);// "Hello, how are you"
 }
console.log(Hello) // Hello is not defined

We see that using hello outside of its block (the curly braces in which it was defined) returns an error. This is because let variables are block-related scope.

let can be updated but not declared

Like var, a variable declared with let can be updated within its scope. Unlike var, a let variable cannot be redeclared within its scope. While this works:

let greeting = "Hey, Hii";
greeting = "Hii, How are you";

this will return the error:

let greeting = "Hey, Hii";
let greeting = "Hii, How are you"; // error: Identifier 'greeting' has already been declared

However, if the same variable is defined in different scopes, there will no error

let greeting = "Hey, Hii";
if (true) {
    let greeting = "Hii, How are you";
    console.log(greeting); // "Hii, How are you"
}
console.log(greeting); // "Hey, How are you"

Why is there no error? This is because both instances are treated as different variables and have different scopes.

This fact makes let a better choice than var. If you use to let, don’t worry if you previously used a name for a variable, since a variable only exists within its scope.

Also, a variable cannot be declared more than once within a scope, then the problem described above that occurs with var occurs, not up.

 

Hoisting of let

Like var, let declarations be hoisted to the top. Unlike var, which is initialized with undefined, the keyword let is not initialized. So if you try to use a let variable before the declaration, you will get a ReferenceError.

 

Const

Variables declared with const contain constant values. const declarations have some similarities to let declarations.

Scope of const

This means that the value of a variable declared with const stays the same within its scope. It cannot be updated or redeclared. So if we declare a variable with const, that doesn’t work either:

const greeting = "Hay, Hii";
greeting = "Hii, How are you?"; // It generate error: Assignment to constant variable.

nor this

const greeting = "Hay, Hii"; 
const greeting = "Hii, How are you?"; // It generate error: Identifier 'greeting' has already been declared

Any const declaration must therefore be initialized at the time of declaration.

This behavior is slightly different when dealing with objects declared with const. Although a constant object cannot be updated, the properties of these objects can be updated. So if we declare a constant object like this:

const greeting = {
    message: "Hay, Hii",
    times: 10
}

We cannot do this

greeting = {
        words: "Hello",
        number: "Ten"
} // error:  Assignment to constant variable.

We can do this

greeting.message = "Hii, How are you?";

 

Hoisting of const

Just like letconst declarations are hoisted to the top but are not initialized.

Thank you so much for reading

Happy Coding

For more details, you can visit MDN Docs

Some more articles on JavaScript

  1. Introduction to JavaScript
  2. Variable in JavaScript
  3. Let var const in JavaScript
  4. JavaScript Data Types

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *