We all have used var, let, and const variables many times in JavaScript but sometimes we all get confused about which is the best variable to use for a particular program. I am writing this blog to understand let, var, and const variables for helping someone to clear their basics regarding the same.
Var
It is the oldest keyword to declare a variable in JavaScript. The scope of it is global or function scope. Variables defined outside the function can be accessed globally and variables defined inside a particular function can be accessed within the function.
It can be updated and re-declared into the scope.
Example -
function f() { var a = 7; console.log(a) } f(); console.log(a);
Output-
7 ReferenceError: a is not defined
Let
It is an improved version of the var keyword. The scope of a let keyword is only block scoped. It cannot be accessible outside the particular block.
It can be updated but cannot be re-declared into the scope.
Example 1-
let a =7; function f() { if (true) { let b = 9 // It prints 9 console.log(b); } // It gives error as it // defined in if block console.log(b); } f() // It prints 7 console.log(a)
Output-
9 ReferenceError: b is not defined 7
Example 2-
let a = 7 if (true) { let a=9 console.log(a) // It prints 9 } console.log(a) // It prints 7
Output-
9 7
Const
It has all the properties same as the let keyword, except the user cannot update it. It cannot be updated or re-declared into the scope.
Example-
const a = { prop1: 7, prop2: 9 } // It is allowed a.prop1 = 3 // It is not allowed a = { b: 7, prop2: 9 }
Top comments (1)
When to use what would be interesting: const -> let, never var.