🙏Namaskaram🙏

Let Var and Const

In javascript "let", "var", and "const" are used to declare variables, but they have some differences in terms of their scope and behavior.

Var

  • Variables declared with "var" are function-scoped. This means that they are accessible within the entire function in which they are defined.
  • If a "var" variable is declared outside of any function, it becomes a global variable, accessible throughout the entire program.
  • "var" variables can be redeclared and reassigned.

Example 1

1  const Example1 = () => {
2    var x = 10;
3    if (true) {
4      var x = 20; // This will overwrite the outer variable
5      console.log(x); // Output: 20
6    }
7
8    const myFunction = () => {
9      var x = 30;
10      console.log("function scope", x); // Output: 30
11    };
12    myFunction();
13
14    const myFunction2 = () => {
15      console.log("Point two", x) // Output: 20
16    }
17    myFunction2()
18
19    console.log(x); // Output: 20
20  };

Let

  • Variables declared with "let" are block-scoped. This means that they are accessible only within the block in which they are defined, such as within loops or conditional statement.
  • "let" variable can be reassigned, but they cannot be redeclared within the same block scope.

Example 2

1  const Example2 = () => {
2    let x = 10;
3    if (10 === 10) {
4      let x = 20; // This creates a new variable in a different scope
5      console.log(x); // Output: 20
6
7      x = 30 // Reassign
8      console.log(x) // Output: 30
9
10      // let x = 40 // wrong ❌  not redclarable
11    }
12    console.log(x); // Output: 10
13  };
14  

const

  • Variables declared with "const" are also block-scoped.
  • "const" variables cannot be reassigned once they are initialized. However, for objects and arrays, the properties and elements can be modified.
  • It is common to use "const" for values that are not intended to be changed.

Example 3

1const Example3 = () => {
2    const x = 10;
3    if (true) {
4      const x = 20; // This creates a new variable in a different scope
5      console.log(x); // Output: 20
6    }
7    console.log(x); // Output: 10
8
9    // x = 30; // cannot reassign
10
11    // const x = 40;  // cannot redclare
12  };
Hii