DEV Community

Cover image for Var vs Let vs Const
Ahnaf Tahmid
Ahnaf Tahmid

Posted on • Edited on

Var vs Let vs Const

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.
  • 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.
  • 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.

    function magicTrick() {
        var rabbit = '🐰';
        console.log(rabbit); // Output: 🐰
    }
    console.log(rabbit); // Output: ReferenceError: rabbit is not defined
    
    
  1. 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.

    var partyAnimal = '🎉';
    function haveFun() {
        console.log(partyAnimal); // Output: 🎉
    }
    haveFun();
    
    
  2. 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.

    if (true) {
        var leakyVar = 'oops';
    }
    console.log(leakyVar); // Output: oops
    
    
  3. Have JavaScript Hoisting Behavior: var gets lifted up! It's like a magical elevator that takes variable declarations to the top of their scope.

    console.log(hoistedVar); // Output: undefined
    var hoistedVar = 'I\\'m hoisted!';
    
    
  4. Redeclarable: var is forgetful. You can redeclare variables without a fuss.

    var color = 'blue';
    var color = 'green';
    console.log(color); // Output: green
    
    
  5. Reassignable: Once a var, always a var. You can change its value anytime.

    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.

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

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

Enter fullscreen mode Exit fullscreen mode

2. Has Function Scope

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

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

Enter fullscreen mode Exit fullscreen mode

3. Has Global Scope

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

let globalCelebrity = "I'm everywhere!";

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

Enter fullscreen mode Exit fullscreen mode

4. Has Block Scope

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

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

Enter fullscreen mode Exit fullscreen mode

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.

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

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

Enter fullscreen mode Exit fullscreen mode

6. Not Redeclarable

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

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

Enter fullscreen mode Exit fullscreen mode

7. Reassignable

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

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

Enter fullscreen mode Exit fullscreen mode

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.
  • 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!"

    const age = 25;
    age = 26; // Uh-oh! Can't change my age now!
    
    
  1. Have Function Scope:
    It means const is like a secret recipe known only within a particular function.

    function cookDinner() {
        const secretIngredient = "love";
        console.log(secretIngredient);
    }
    
    cookDinner(); // Outputs: love
    console.log(secretIngredient); // Error! I can't see the secret ingredient outside!
    
    
  2. Have Global Scope:
    This is like broadcasting your announcement to the whole world. Everyone can access it from everywhere!

    const globalLanguage = "JavaScript";
    
    function sayHello() {
        console.log(`Hello from ${globalLanguage}!`);
    }
    
    sayHello(); // Outputs: Hello from JavaScript!
    
    
  3. Have Block Scope:
    It's like having a magic spell that only works within a specific area.

    if (true) {
        const magicNumber = 7;
        console.log(magicNumber); // Outputs: 7
    }
    
    console.log(magicNumber); // Error! Magic number disappears outside the block!
    
    
  4. Not Have JavaScript Hoisting Behavior:
    Unlike some folks who can jump up before you expect them to, const stays right where you put it.

    console.log(pet); // Error! Can't access pet before initialization
    const pet = "dog";
    
    
  5. 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!

    const favoriteFood = "pizza";
    const favoriteFood = "sushi"; // Error! I already have a favorite food!
    
    
  6. Not Reassignable:
    It's like saying, "I've made up my mind, and I won't change it."

    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

Top comments (0)