Day 3 of #100daysofjs

Day 3 of #100daysofjs

what is var, let and const?

  1. var:

    • var is the oldest way to declare variables in JavaScript.

    • Variables declared with var have function scope, meaning they are accessible within the function they are declared in.

    • If var is declared outside any function, it has global scope and can be accessed from anywhere in the script.

    • var does not have block scope, so variables declared with var are accessible even outside the block they are defined in.

    • var allows you to redeclare and reassign variables multiple times throughout the code, which can lead to unexpected behavior and bugs if not used carefully.

  2. let:

    • let is a newer way to declare variables introduced in modern JavaScript (ES6).

    • Variables declared with let have block scope, meaning they are limited to the block of code they are defined in (e.g., within loops or conditional statements).

    • Variables declared with let can be reassigned within their scope.

    • Unlike var, let does not allow the redeclaration of the same variable within the same scope, which can help prevent accidental errors and conflicts in your code.let:

      • let is a newer way to declare variables introduced in modern JavaScript (ES6).

      • Variables declared with let have block scope, meaning they are limited to the block of code they are defined in (e.g., within loops or conditional statements).

      • Variables declared with let can be reassigned within their scope.

      • Unlike var, let does not allow the redeclaration of the same variable within the same scope, which can help prevent accidental errors and conflicts in your code.

  3. const:

    • const is also introduced in modern JavaScript (ES6).

    • Variables declared with const also have block scope.

    • const stands for "constant" and is used to declare variables that should remain unchanged after being assigned a value.

    • const variables are read-only and cannot be reassigned once defined.

    • While the variable itself cannot be reassigned, if the value is an object or an array, its properties or elements can still be modified.

In short

  1. Var is globally scoped while let and const are block scoped.

  2. var can be updated & redeclared within its scope.

  3. let can be updated but not redeclared.

  4. const can neither be updated nor be redeclared.

  5. var variables are initialized with undefined where as let and const variables are not initialized.

  6. const must be initialized during declaration unlike let and var.

Did you find this article valuable?

Support Arpan Mukherjee's Blogs by becoming a sponsor. Any amount is appreciated!