Var vs Let vs Const
Tags: javascript, variables, letconst, beginners
Published: 2024-02-23 07:10:23

## Var vs Let vs Const

In this article, I will teach you everything you need to know about the differences among var, let, and const. So, let's get started! ✌

## **All You Need To Know**

`var` has been used in all web applications since ES6 (2015). It can be a bit confusing for beginners. If you need support for older versions, you must use `var`. But don't worry about it! Nowadays, developers use a bunch of libraries and frameworks like React.js, Angular.js, Vue.js. These frameworks check browser compatibility. So, let's break down the `var` keyword.

## **Var Keyword Rules**

- Used in older applications.
- Has function scope.
- Has global scope.
- Does not have block scope.
- Has JavaScript hoisting behavior.
- Redeclarable.
- Reassignable.
1. **Used in Old Applications**: Imagine `var` as the old grandpa of JavaScript. It's been around for a while and has seen a lot, but newer generations (like `let` and `const`) have taken over.
2. **Have Function Scope**: Think of `var` like a magician who performs tricks inside their hat. Whatever they declare with `var` stays inside that function and isn't visible outside.
    
    ```jsx
    function magicTrick() {
        var rabbit = '🐰';
        console.log(rabbit); // Output: 🐰
    }
    console.log(rabbit); // Output: ReferenceError: rabbit is not defined
    
    ```
    
3. **Have Global Scope**: `var` is like that one person at a party who talks to everyone and is heard by all. Variables declared with `var` outside any function are accessible globally.
    
    ```jsx
    var partyAnimal = '🎉';
    function haveFun() {
        console.log(partyAnimal); // Output: 🎉
    }
    haveFun();
    
    ```
    
4. **Not have Block Scope**: `var` doesn't care about blocks. It's like a reckless driver who ignores traffic signals. Variables declared with `var` leak outside blocks.
    
    ```jsx
    if (true) {
        var leakyVar = 'oops';
    }
    console.log(leakyVar); // Output: oops
    
    ```
    
5. **Have JavaScript Hoisting Behavior**: `var` gets lifted up! It's like a magical elevator that takes variable declarations to the top of their scope.
    
    ```jsx
    console.log(hoistedVar); // Output: undefined
    var hoistedVar = 'I\\'m hoisted!';
    
    ```
    
6. **Redeclarable**: `var` is forgetful. You can redeclare variables without a fuss.
    
    ```jsx
    var color = 'blue';
    var color = 'green';
    console.log(color); // Output: green
    
    ```
    
7. **Reassignable**: Once a `var`, always a `var`. You can change its value anytime.
    
    ```jsx
    var mood = 'happy';
    mood = 'sad';
    console.log(mood); // Output: sad
    
    ```
    

# Let All are Need To Know

You can say let is a alternative of var keyword. Modern web application use it as a alternative modern version var. It comes in ES6. The main difference of let and var is Let have block scope and var have no block scope.  Let is not redeclarabled and var is redeclarabled

## Let Keyword Rules

- Used In Modern Applications as an Alternative to `var`
- Has Function Scope
- Has Global Scope
- Has Block Scope
- Does Not Have JavaScript Hoisting Behaviour.
- Not Redeclarabled
- Reassignable.

### 1. Used In Modern Applications as an Alternative to `var`

Think of `let` as the cooler, newer version of `var`. It's like swapping out your old flip phone for a shiny new smartphone.

```jsx
// Old school
var oldSchool = "I'm a dinosaur";

// Modern and hip
let newHotness = "I'm the future";

```

### 2. Has Function Scope

`let` behaves well inside functions. It's like a magician who only performs within their stage.

```jsx
function myFunction() {
  let insideFunction = "I'm inside!";
  console.log(insideFunction);
}

myFunction(); // Output: "I'm inside!"
console.log(insideFunction); // Throws an error, because 'insideFunction' is only known inside the function

```

### 3. Has Global Scope

`let` can play on the big stage too, outside of functions. It's like a celebrity everyone knows.

```jsx
let globalCelebrity = "I'm everywhere!";

function anotherFunction() {
  console.log(globalCelebrity); // Output: "I'm everywhere!"
}

```

### 4. Has Block Scope

`let` is like a chameleon; it changes depending on where it's put. It's like a master of disguise!

```jsx
if (true) {
  let insideBlock = "I'm inside the block!";
  console.log(insideBlock);
}

console.log(insideBlock); // Throws an error, because 'insideBlock' only exists within the block

```

### 5. Does Not Have JavaScript Hoisting Behavior

`let` stays right where you put it. It's like glue, it sticks to where it's declared.

```jsx
console.log(hoistedVar); // undefined
var hoistedVar = "I'm hoisted!";

console.log(hoistedLet); // Throws an error
let hoistedLet = "I'm not hoisted!";

```

### 6. Not Redeclarable

`let` is like a stubborn pet; it doesn't like being told what to do twice.

```jsx
let myVariable = 42;
let myVariable = "Oops! I did it again"; // Throws an error, because 'myVariable' is already declared

```

### 7. Reassignable

`let` is flexible; it can change its value whenever it wants. It's like a shape-shifter!

```jsx
let mutableVariable = "I can change";
mutableVariable = "I'm a whole new variable now!";
console.log(mutableVariable); // Output: "I'm a whole new variable now!"

```

# Const All are Need To Know

Const means Constant [Not Changable]. It comes in ES6. These is same to let keyword. But the difference it is not reassignable  and let is reassignable

## Const Keyword Rules

- Used In Modern Application as a Alternative of var
- Has Function Scope
- Has Global Scope
- Has Block Scope
- Does Not Have JavaScript Hoisting Behaviour.
- Does Not Redeclarabled
- Not Reassignable.
1. **Used In Modern Applications as an Alternative to var**:
Think of `const` as your loyal friend who won't change their mind once they've made a decision. If you declare something with `const`, it's like saying, "This is it, I'm sticking with it!"
    
    ```jsx
    const age = 25;
    age = 26; // Uh-oh! Can't change my age now!
    
    ```
    
2. **Have Function Scope**:
It means `const` is like a secret recipe known only within a particular function.
    
    ```jsx
    function cookDinner() {
        const secretIngredient = "love";
        console.log(secretIngredient);
    }
    
    cookDinner(); // Outputs: love
    console.log(secretIngredient); // Error! I can't see the secret ingredient outside!
    
    ```
    
3. **Have Global Scope**:
This is like broadcasting your announcement to the whole world. Everyone can access it from everywhere!
    
    ```jsx
    const globalLanguage = "JavaScript";
    
    function sayHello() {
        console.log(`Hello from ${globalLanguage}!`);
    }
    
    sayHello(); // Outputs: Hello from JavaScript!
    
    ```
    
4. **Have Block Scope**:
It's like having a magic spell that only works within a specific area.
    
    ```jsx
    if (true) {
        const magicNumber = 7;
        console.log(magicNumber); // Outputs: 7
    }
    
    console.log(magicNumber); // Error! Magic number disappears outside the block!
    
    ```
    
5. **Not Have JavaScript Hoisting Behavior**:
Unlike some folks who can jump up before you expect them to, `const` stays right where you put it.
    
    ```jsx
    console.log(pet); // Error! Can't access pet before initialization
    const pet = "dog";
    
    ```
    
6. **Not Redeclarable**:
Once you've introduced something with `const`, you can't introduce another thing with the same name in the same scope. It's like having a name tag that sticks!
    
    ```jsx
    const favoriteFood = "pizza";
    const favoriteFood = "sushi"; // Error! I already have a favorite food!
    
    ```
    
7. **Not Reassignable**:
It's like saying, "I've made up my mind, and I won't change it."
    
    ```jsx
    const skyColor = "blue";
    skyColor = "red"; // Error! Can't change the color of the sky!
    
    ```
    

# Conclusion

In summury , Most of the case we use const. This is good practice to use const to declare array , object and Fixed Value like PI. If the value is changable we use let. I recommended you to not use var always use let and const keyword from now. If you find any wrong information in my first article contact me.

## Happy Coding!! 😀

💌 ahnaftahmid802@gmail.com