Programming Tutorials

let, const, and var in JavaScript

By: Stella in Javascript Tutorials on 2023-04-25  

In JavaScript, let, const, and var are used for declaring variables, but they have different scopes and behaviors. Here are the main differences:

  1. var: This keyword has function scope, which means that the variable declared with var can be accessed within the function in which it was defined. If a variable is declared with var outside of any function, it will be a global variable and can be accessed throughout the code. var can be re-declared and updated.

Example:

function foo() {
  var x = 5;
  if (true) {
    var x = 10;
    console.log(x); // Output: 10
  }
  console.log(x); // Output: 10
}
  1. let: This keyword has block scope, which means that the variable declared with let can be accessed only within the block in which it was defined (for example, within an if statement, for loop, or function). let can be updated but not re-declared.

Example:

function foo() {
  let x = 5;
  if (true) {
    let x = 10;
    console.log(x); // Output: 10
  }
  console.log(x); // Output: 5
}
  1. const: This keyword also has block scope, but it is used for declaring constants. The value of a const variable cannot be changed or re-declared.

Example:

function foo() {
  const x = 5;
  if (true) {
    const x = 10;
    console.log(x); // Output: 10
  }
  console.log(x); // Output: 5
}

In general, it is recommended to use const for values that will not be changed, let for values that will be changed, and var for global variables. However, the choice of which keyword to use ultimately depends on the specific needs of the code and the programmer's preference.






Add Comment

* Required information
1000

Comments (1)

Avatar
New
Derricksays...

var declarations can have surprising behaviors (for example, they are not block-scoped), and they are discouraged in modern JavaScript code.

If you declare a variable without assigning any value to it, its value is undefined. You can't declare a const variable without an initializer, because you can't change it later anyway.

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)