let  VS var VS const

let VS var VS const

Understand the var, let and const in Javascript.

ยท

8 min read

Hi folks ๐Ÿ‘‹๐Ÿป, hope you are doing extremely well ๐Ÿ˜Ž. In this quick article, we will discuss the different variable-defining methods in javascript.

in short, javascript provides us to define variables using three keywords var, let, and const

History of variable defining keywords.

Javascript was invented by Brendan Eich in the year 1995. It was developed for Netscape 2 and became the ECMA-262 standard in 1997. at the initial phase of javascript developers has a single keyword to declare a variable that was var keyword.

In the year of 2015, javascript introduced the second major revision and it is also known as ECMAScript 2015, ES6, and ECMAScript 6 terms.

in ES6 there were multiple new features and two of them were the let and const keywords for variable declaration.

The `var` keyword

In general, we declare the variable using the var keyword for instance,

var a = 10;
console.log(a)  /// OUTPUT 10

along with the declaration, the var keyword has some special properties.

Redeclarable, changable.

The variable that is defined previously with the var keyword can be redeclared and updated without any error.

var x = 10; // variable declared
console.log(x) // OUTPUT 10
var x = 20;  // variable redeclared
console.log(x) //OUTPUT 20
x = 21;   //  variable updated
console.loog(x) //OUTPUT 21

Function Scoped

var defines the variable with the global scoped or function scoped. Oh! you might hear this a lot of times but what exactly it is? see the above points,

  • So actually if you define a variable outside a function will be accessible in the whole window.
<script>
var roll_no = 21;
console.log(roll_no); //OUTPUT  21
console.log(window.roll_no); //OUTPUT  21
</script>
<!-- 
here you can se variable roll_no declared outside the function and now it is avaibale in whole window.
note: you can check all window properties of the browser using window.<something>
-->
  • var is function scoped when it is defined inside the function and the variable will be accessible in the function.
  1 function myfunc(){
  2     var age = "103";
  3 }
  4 myfunc(); 
  5 console.log(age) // ERROR:: ReferenceError: age is not defined
  • Variables declared inside a { } block can be accessed from outside the block.
  1 {
  2   var sayHello = "Hello!";
  3 } 
  4 console.log(sayHello) // OUTPUT:: Hello

that's pretty cool stuff ๐Ÿ˜ฏ hope you'll remember these points.

let's have a mixed example and you guys please try to solve the problem ๐Ÿ˜„ and please let me know in the comment what will be the output.

 1 var x = 10;
  2 function f(){
  3     var x = 50;
  4     if(true){
  5         var b = "Neetesh"
  6     }   
  7     console.log(x, " ::Inside the function");
  8     console.log(b , " ::can be access outside the block and inside the functin")
  9 }   
 10 f()
 11 console.log(x, " ::In the same block")
 12 console.log(b)

hope you guys tried to solve it and let me explain in case you found this something confusing.

  1 var x = 10; // global scoped
  2 function f(){
  3     var x = 50;   // redeclare the varaible x
  4     if(true){
  5         var b = "Neetesh" // declared inside the block
  6     }   
  7     console.log(x, " ::Inside the function"); // x = 5
  8     console.log(b , " ::can be access outside the block and inside the functin") // b = "Neetesh"
  9 }   
 10 f()
 11 console.log(x, " ::In the same block") // x = 10
 12 console.log(b) // ERROR ReferenceError: b is not define

In the above example,

the variable x that has the value 10 has been redeclaring inside function f() but due to function, the scope declared/redeclared variable can be accessible inside the function only not outside the function, for example, line 11, x contains the value 10, not 50.

so exactly we learn that the declared or redeclared variable inside the function is only accessible inside the function.

if you look at line 5 you will find that variable b is declared in the if block and still accessible at line 8 inside the function and will throw an error if we try to access outside the respected function ex:- line 12.

Default value

The var defined variable holds the undefined value before the actual declaration due to hoisting.

  1 console.log(name)  // used before declaration. OUTPUT:: undefined
  2 var name = "Neetesh";
  3 console.log(name) // OUTPUT Neetesh

While hoisting javascript automatically initializes the variable with undefined till the variable has been initialized with a value.

  1 // ---------- dead zone ------
  2 var name; // has value undefined
  3 
  4 // ------ your code -----
  5 console.log(name) // OUTPUT:: Neetesh
  6 name = "Neetesh"
  7 console.log(name) // OUTPUT:: Neeteshtside the function block it it will be available in entire window.

so what if we redeclare the variable inside the function๐Ÿค” ? Let's see,

  1 var age = 180
  2 function f(){
  3   console.log(age) // OUTPUT 180
  4 } 
  5 f()
  6 
  7 // if we redeclare
  8 var age = 180
  9 function f(){
 10   console.log(age) // OUTPUT undefined
 11   var age = 90;
 12   console.log(age) // 90 
 13 } 
// Here you can see we got undefined because of hoisting of functional variable.

Alright, folks how good is the var right๐Ÿ˜ƒ?

Actually not because some properties of the var actually, cause a bug.

You might think "How"?

let me explain...

Cons of `var` keyword

Can redeclare the variable

let's say you have defined a variable at line 40 some code and another developer has declared the same variable at line 1200 because he doesn't know and redeclared the variable, changed the variable's data and it will raise a new bug.

at some point, we want the value that was declared at line no 40 but due to the declaration that value has been changed.

For loops, this Hoisting gets relevant. It leads quickly to bugs and takes care of your face wondering in front of the screen.


var items = ["abc", "def"];

for (var i = 0; i < items.length; i++) {
  setTimeout(function () {
    console.log(items[i])
  }, 0);
}

You might guess ๐Ÿฅธ the output will be abc and def but here is the twist and the output will be undefined and undefined ๐Ÿ˜๏ธ.

This is because of hoisting. Declaring a variable with var in our for the loop doesnโ€™t limit its scope. Since its existence extends beyond that for loop when the value is evaluated by the setTimeout() callback, we got the last value it was set to. (it gets set to 3, which is why the for loop stops).

All of these issues can be resolved using let keyword.

The `let` keyword

let is another way to declare the variables introduced in ES6 that actually t solves the hoisting problems and improves of var declarations.

Can't redeclare

unlike var the variable defined with the keyword let can't be declared.

let name = "Neetesh"
let name = "Neetesh" // Error: Identifier 'name' has already been declared

Block-Scoped

let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

a block is the part of code that is bound in {} braces .

A variable declared with let inside a block will be available only inside the block.

  1 let x = 10;
  2 if (x < 11){
  3     let x = 11;
  4     console.log(x) // Output: 11
  5 }
  6 console.log(x) // Output: 10

In the above example, you might think an error will raise at line no. 3 but actually not because of the block. If we define some variables Inside the block, they will be treated as new variables that will be available in the same block only.

No Default Value

The let variables are also hoisted on the top.

unlike the var variables, which are initialized undefined as a default value, the let keyword is not initialized. The use of the variable before declaration will throw an Reference error.

console.log(name)
let name = "Joe"
// ReferenceError: Cannot access 'name' before initialization

The `const` keyword

Variables defined with const cannot be Redeclared, Reassigned and have Block Scope.

  1 const a = 10;
  2 const a = 15;
  3 //SyntaxError: Identifier 'a' has already been declared
  1 const a = 10;
  2 a = 15;
  3 //TypeError: Assignment to constant variable

But here is one thing to note, you can change the values of Array and Object.

  1 const a = [1,2,3]
  2 a[1] = 5
  3 console.log(a) // Output:: [1,5,3]
  4 
  5 const b = {age: 19}
  6 b.age = 109;
  7 console.log(b) // Output:: {age: 109}

But you still can't do this:

  1 const a = [1,2,3]
  2 a = [4,5 // TypeError: Assignment to constant variable.]
  3 
  4 
  5 
  6 const b = {age: 19}
  7 b = [age: 109] //TypeError: Assignment to constant variable.

Outro

I saw you have read the article ๐Ÿ˜ƒ and have still some confusion, you can ask me in the comment section and also can give some feedback.

Thanks for the reading and wishing you a great day ๐Ÿ™ƒ.

Meme Of The Day

ย