Ankit Shrivastava
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Difference between Var, Let, and const in javascript. ### Abstract If we were to consider the programming in javascript as multi-flavored ice cream, methods of declaring variables are the available flavors. Understanding the difference between the variables leads to writing error-free and easy to debug/understand code. ### Scope of Article In this post, you will learn: * What is the difference between `var`, `let`, and `const` variables. * How to declare a variable and initialize. * Scoping and hoisting and how it works with different variables. * Declaration, re-declaration, initialization, and updation behavior of different variables. ### Introduction to the Difference Between Var, Let, and Const In javascript `var`, `let`, and `const` is the keyword to declare variables in javascript.`var` keyword is the legacy method to declare variables where `let` and `const` are modern and preferred ways which are introduced in ES2015(ES6) update. Let's understand the variable declaration and initialization using these keywords. ### Variable Declaration vs Initialization To store a value in javascript we need variables, to make one we have to declare it first then initialize it. let's start with variable declaration first - #### Variable Declaration To declare a variable we have to write a valid keyword than the name of the variable, like this - ```javascript= var myName; ``` #### Variable Initialization To initialize the declared variable above we have to write the initialization sign(`=`) followed by the value we want to store, like this - ```javascript= var myName = "Ankit"; ``` Above we declared and initialize the `var` variable, the same process will be followed for `let` and `const` variables. At this point, `var`, `let`, and `const` all look the same, but there is a difference between them. It shows `undefined` if we try to access the `var` variable before the declaration, but doing the same with the `let` and `const` variable throw error. Let's take an example to understand it - ```javascript= console.log(myFirstName); //output => undefined console.log(mySecondName); //output => ReferenceError var myFirstName = "ankit-1"; let mySecondName = "ankit-2"; const myThirdName = "ankit-3"; ``` Above, in the first line printing the value of a `var` variable initialized by a string value, out-put is `undefined`, doing the same in the second and third line with `let` and `const` variable which throws `ReferenceError`. This is happening because of the difference between the scope of the variables. Now, Let's understand scoping and how it works with different types of variables. ### Function-scope vs Block-scope #### Scope Scope stands for the area inside the code where variables will be available to use. There are two types of scope in javascript - * Function scope * Block scope ##### 1.Function scope Variable having the function scope is available to use everywhere inside the function is defined and the `var` variable has the function scope by default. Let's take an example to understand this - ```javascript= function myFun() { var myName = "ABC"; if(true) { var myAge = "12"; console.log(myName); } console.log(myAge); } myFun(); //output => "ABC" "123" console.log(myName); //output => ReferenceError console.log(myAge); //output => ReferenceError ``` Above, we have a `myFun` function with two `var` variables, one is `myName` defined on top and another is `myAge` defined inside the conditional `if` block where we also printing the `myName` variable, then in the last line printing the `myAge` variable. Next, calling the `myFun` function which prints "ABC" "123" on the console, but when tried to print the `myName` and `myAge` variable outside the function scope gives `ReferenceError`. Notice how in the last line of the function we printed the `myAge` variable defined inside the `if` block, this verifies the fact that by default `var` variable has the scope of function and it will be available to use everywhere inside the function it defined. ##### 2.Block scope variable having the block scope is available to use only inside the block it defined, by default `let` and `const` variable has the block scope. A block is represented by an opening and closing curly bracket (`{}`) now, let's take an example to understand this - ```javascript= function myFun() { let myName = "ABC"; if(true) { let myAge = "12"; console.log(myName); } console.log(myAge); } myFun(); //output => "ABC" "ReferenceError: myAge is not defined" ``` Above, we have a `myFun` function with two `let` variables, one is `myName` defined on top and another is `myAge` defined inside the conditional `if` block where we also print the `myName` variable, then in the last line printing the `myAge` variable. Next, calling the `myFun` function as result prints "ABC" "ReferenceError: myAge is not defined" on console, it's saying `myAge` variable is not defined because it's declaration is inside the `if` block and `let` variable have block scope which is not accessible outside the block it defined. Great! Now we understand the basic difference between the variables, let's deep dive to understand it further. ### What is the var variable in JS? (Include these points: Hoisting of var, The var Problem too) `var` variable are declared using `var` keyword this is the legacy method to declare a variable in javascript it has function scope by default and gets **hoisted** on top of scope which makes `var` variable unique from other variables. #### Hoisting in var variable Hoisting is a behavior of javascript which hoist the variables on top of it's scope, `var` variables get hoisted and initialized with `undefined`. let's take an example to understand this - ```javascript= console.log(myName); //output => undefined var myName = "ABC"; ``` Above, in the first line we tried to print the `myName` variable on the console before it's a declaration as result it prints `undefined` and the reason is `var` variable gets hoisted on top of the scope and uninitialized with `undefined`, which look something like this - ```javascript= var myName = `undefined`; console.log(myName); //output => undefined myName = "ABC"; ``` Above, it's clear how the declaration of variable gets moved on top of the scope and initialized with `undefined`. There are some other problems with using `var` variable. #### The var Problem- There were two main problems with the `var` variable, which were redeclaration and reinitialization- ##### 1.Redeclaration Redeclaration was the biggest problem with the `var` variable, which make our code hard to read and debug. Let's take an example to understand redeclaration - ```javascript= var myName = "ABC"; console.log(myName) //out-put => "ABC" // redeclarating `myName` var myName = "XYZ"; console.log(myName); //out-put => "XYZ" ``` Above, we declared a `myName` variable and printed the value on console but again redeclare the `myName` variable with a different value which overrides the previous value, this behavior of declaring a variable with the same name is known as redeclaration of `var` variable. ##### 2.Reinitialization Reinitialization of the `var` variable was also a big problem which didn't allow us to use constant variables which are variables holding a constant value in the whole program and don't reinitialize. Let's take an example to understand it - ```javascript= var myVal = 10; console.log(myVal); //output => 10 //reinitializing `myval` myVal = 15; console.log(myVal) //output => 15 ``` Above, we declared a `myName` variable and printed it on the console then reinitialize it with another value this time printing on the console gives an updated value which verifies the fact that the `var` variable can be reinitialized. **Takeaway:** `var` variables are function scoped and updation and re-declaration both are allowed in `var`. Now, let's talk about the `let` variable which is more frequently used instead of `var`. ### What is the Let variable in JS? (Include these points: block-scoped, an example of Let, updated but not re-declared, Hoisting of let too) `let` variables are declared using `let` keywords and it was introduced in the ES2015(ES6) version of JavaScript and by default `let` variables have block scope. #### Block scoped variable having block scope is available to use only inside the block it defined. Let's understand it by an example - ```javascript= let myVal = 10; if(true) { let myVal = 20; console.log(myval); //output => 20 } console.log(myVal); //output => 10 ``` Above, we declared two `myVal` variables, one is defined on top and another is defined inside the `if` block which is also printed on the console than `if` block closed, in the last line printed the `myVal` on the console again. As result it prints "20" and "10" on the console, the reason is the following - - `let` variables are block scope so `myVal` variable defined inside the `if` block will not be accessible outside the `if` block. - It prints "20" for `myVal` variable inside the `if` block than "10" for `myVal` declared on top. ### updated but not re-declared #### `let` variable can be updated `let` variable will be updated after reinitialization but it can't be re-declared. Let's understand it will an example - ```javascript= let myVal = 10; console.log(myVal); //output => 10 //reinitializing myVal = 20; console.log(myVal); //output => 20 ``` Above, in the first line `myVal` variable is declared and printed in the second line which prints "10" on console, then `myVal` gets reinitialized and again printed which prints "10", this changes in the printed value verify that `myVal` variable gets updated. #### No re-declaration of `let` variable Variable declaration with the same is called re-declaration which is not allowed in the `let` variable - ```javascript= let myVal = 10; let myVal = 20; console.log(myVal); //output => SyntaxError ``` Above, `myVal` variable is declared in the first line and again re-declared in the second line which is not allowed to do in `let`, as a result when we tried to print `myVal` on the console it gives `SyntaxError`. This behavior of the `let` variable verifies that the `let` variable can't be re-declared. ### Hoisting of let Variable declared using `let` also get hoisted but remains uninitialized as a result if we try to access the `let` variable before it is declared, we get the `SyntaxError`, here is an example - ```javascript= console.log(myVal); //output => ReferenceError let myVal = 10; ``` Here we tried to access the `myVal` variable before it is declared and get `ReferenceError` as result. **Takeaway:** `let` variables are block-scoped updation are allowed but re-declaration is not allowed in `let`. In the `let` variable we can not declare a constant variable let's explore the `const` variable which allows it. ### What is the Const variable in JS? (Include these points: const declarations are block-scoped, cannot be updated or re-declared, Hoisting of const too) `const` variable are declared using `const` keywords which is also introduced in the ES2015(ES6) version of JavaScript, by default `const` variables has block scope. Let's understand it with an example - ```javascript= if(true) { const myVal = 200; console.log(myVal); //output => 200s } console.log(myVal); //output => ReferenceError ``` Above, we declared `myval` variable inside the`if` block than printed it on console , but get `ReferenceError` on trying to access the `myVal` from outside because variable having block scope are only accessible inside the block it declared. When we were using the `let` variable there was a problem of updation of variable which `const` variable solved. #### cannot be updated or re-declared `const` variable can not be updated or re-declared let's talk about the updation first - #### `const` variable cannot be updated `const` variable gives the power to use constant variables inside our code, `const` variable did not get updated in any case let's understand it with an example - ```javascript= const myVal = 10; console.log(myVal); //output => 10 //tried reinitialization myVal = 20; console.log(myval); //output => TypeError ``` Above, in first line we declared a `myVal` variable in second line printed it on console as result it prints `10` but when we tried to print the `myVal` after reinitialization it show `TypeError` because `const` variable cannot be updated. #### `const` variable cannot be re-declared Declaration of variables is also not allowed in `const` variable, meaning we can not declare two variables with the same name in a single block. Here is an example - ```javascript= const myVal = 20; const myVal = 30; console.log(myVal); //output => SyntaxError ``` Above, in first line we declared a `myVal` variable then in the next line we again declared the `myVal` variable and because `myVal` is already declared inside the global scope(parent scope) it will throw a `SyntaxError`. ### Hoisting of `const` variable `const` variable also gets hoisted but it did not get assigned and remains uninitialized as a result if you will try to access the `const` variable before it is declared it will show `ReferenceError`. Here is an example - ```javascript= console.log(myVal); //output => ReferenceError const myVal = 10; ``` Above, we tried to access the `myVal` variable before it is declared as result we get `ReferenceError`. ### Difference between var, let & const (Tabular structure) Great! now we know the difference between `var` `let` and `const`, let's summerise it. | var | let | const | | -------- | -------- | -------- | | `var` variable are declared using var keyword | `let` variable are declared using `let` keyword | `const` variable are declared using `const` keyword | | `var` variable has the function scope | `let` has the block scope | `const` variable also has the block scope| |It gets hoisted to the top of its scope and initialized with undefined. | It also gets hoisted on top of its scope but remains uninitialized. | It also gets hoisted on top of its scope but remains uninitialized.| | It can be updated or re-declared. | It can be updated but can't be re-declared. | It can't be updated or re-declared.| |It's an old way to declare variables.|It's a new way to declare variables introduced in ES6. | It's also a new way to declare variables which introduces in ES6.| ### Conclusion * `var` is an old way to declare variables, `let` and `const` are modern ways introduced in ES6. * `var` variable has the function scope, `let` and `const` variable has the block scope. * `var` variable can be updated and re-declared, `let` variable only be updated not re-declared and `const` variable can’t be updated or re-declared. ---- ----

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully