Difference between let, var and const with example

Today we will let you know the difference between let, var and const with example. Everyone knows about the const and var but in this article we will show you the example which will help you to understand about the let, var and const.

Difference between let, var and const with example, Var, let and const- what’s the difference?, difference between let and var and const in javascript, js difference between let and var and const in typescript.

var is a global scope variable where let is a block scope variable.

Let’s take an example of let and var for different types of cases. You can check it via JS Bin

Difference between let and var

  1. Outside of a function
  2. Inside a function
  3. Inside a block
  4. Loop
  5. Loop with closure
  6. Redeclaration

1. Outside of a function

When you declare a variable using var and let outside of a function then var will create a property in the global object whereas let don’t create a property in global object.

2. Inside a function

Let’s declare the variables in function using var and let. When you try to access that variable outside of the function then it will throw an error.

3. Inside a block

If you declared the variable within the block then only let variable can’t be accessed outside that block.

4. Loop

When you define the variables in loop and try to access it then let variable will throw an error.

5. Loop with closure

Let’s take an example with setTimeout and try to print log of the variables.

Based on the logs we can say that it will be safe to use let for loops with closure.

6. Redeclaration

While you work with the strict mode then re-declaring the variable with let will prompt the error.

Const

1. Can’t be re-assign

If you are declaring the variable using const then you can’t be re-assigned it.

Note: While you are working with object/array then you can assign a value to the property of the variable but you can not assign a value to the variable.

2. Required Initializer

You must specify a value while declaring a variable using const.

Check out more article on JavaScript for React.

Thank you for reading. Happy Coding!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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