Let V/s Var in JavaScript
Tags: webdev, javascript, beginners, programming
Published: 2023-10-26 05:12:50

let's dive deeper into the differences between `let` and `var` in the context of the code snippet you provided and explore the underlying concepts of JavaScript.

- **Variable Declaration and Scope:**
    
    - **`var`:** Variables declared with `var` are function-scoped or globally scoped, but they are not block-scoped. This means that a variable declared with `var` is available throughout the entire function or globally if declared outside of any function.
        
    - **`let`:** Variables declared with `let` are block-scoped. This means that they are only accessible within the block (curly braces) in which they are declared. Block scope can be a loop, an if statement, a function, or any other block of code.
        
- **Hoisting:**
    
    - **`var`:** Variables declared with `var` are hoisted to the top of their containing function or global scope. However, only the declaration is hoisted, not the initialization. This means you can access a `var` variable before it's declared, but it will have an initial value of `undefined`.
        
    - **`let`:** Variables declared with `let` are also hoisted, but they are not initialized. If you try to access a `let` variable before it's declared, you'll get a ReferenceError. This behavior helps catch potential issues early.
        
- **Closures:**
    
    - **`var`:** Variables declared with `var` in a loop often lead to unintended closure-related issues, as we saw in your initial code snippet. This is because they capture the variable by reference and not by value, causing all closures to share the same reference.
        
    - **`let`:** Variables declared with `let` in a loop create a new variable with each iteration, effectively capturing the value of the variable at that iteration. This behavior is why `let` is often preferred in situations where you want to avoid closure-related problems.
        

### Global declaration example:

```js
var color = 'red'
let age = 30
//note here color variable is attached to the window object so
console.log(window.color) // red
console.log(windiw.age)// undefined
```

So here you can see when defined as global variables the var attaches that variable to the window object, now this is unwanted in our code because the window contains many properties and if any of variable with the same name created it will changes it.

### Block declaration example

```js

const test = ()=>{
  for (let i = 0; i < 3; i++) // here defined with let
    console.log(i)
  console.log(i) // reference error i is not defined
}
test()

```

here as we can see the let has the block scope so the value of i is not accessible to the outside of the block of the for loop 

However if we change the declaration of let with the var variable we can see that this value will be accessible outside of the loop as in the following example

```js

const test = ()=>{
  for (var i = 0; i < 3; i++) // here defined with var
    console.log(i)
  console.log(i) // 1 2 3 
}
test()

```

here the value of i runs till 2 while the loop condition was true, then i updates again to 3 and the condition is then false, so it exits the block of the for loop and then prints the value outside of the block which is inside the function i.e, 4 

Here is another clear example 

```js
const test = ()=>{
  for (var i = 0; i < 3; i++) // here defined with let
    console.log('inside for loop' + i)
    
  console.log('inside test function'+i) // reference error i is not defined
  if(i === 3){
    console.log('I reached in if block')
  }
}
test()

//inside for loop0
//inside for loop1
//inside for loop2
//inside test function3
//I reached in if block
```


### Variable declaration, nuances of var declaration

So, when we declare the variable with var, it is hoisted to the global scope, *note only the declaration is hoisted and not the variable initializing*

for example consider this cheeky code

```js
console.log(x); // undefined
var x = 5;

```
so here can be seen that the variable x is accessed before it is declared, let us see how this code is interpreted behind the scenes

```js
var x; // Declaration is hoisted
console.log(x); // undefined
x = 5; // Initialization happens here

```

These are the simple examples on what are the basic differences between let and var. In order to deep dive into JavaScript it is still a good practice to learn the how the language behaves on practical use-case.