What are the differences between variables created using let, var or const?

In JavaScript, there are three ways to create variables: using the var keyword, the let keyword, and the const keyword. Each of these keywords has its own characteristics and behaves differently in certain situations.

The var keyword is the oldest way to create variables in JavaScript. Variables created using var are function scoped, which means that they are only accessible within the scope of the function where they are defined. If a variable is declared with var inside a function, it can be accessed anywhere within that function, even before it's declared. This is known as "hoisting".

function example() {
    console.log(x); // undefined
    var x = 5;
    console.log(x); // 5
}
example();

In this example, the variable x is declared inside the function example, and it can be accessed before it's declared, which will return undefined.

The let keyword was introduced in ECMAScript 6 (ES6) as a new way to create variables. Variables created using let are block-scoped, which means that they are only accessible within the block of code where they are defined. Unlike var, variables declared with let cannot be accessed before they are declared and this is known as the "temporal dead zone" .

function example() {
    console.log(x); // ReferenceError: x is not defined
    let x = 5;
    console.log(x); // 5
}
example();

In this example, the variable x is declared inside the function example, if you try to access it before it's declared, it will return a ReferenceError.

The const keyword was also introduced in ES6 and it is similar to let in that it creates a block-scoped variable, and it also cannot be accessed before it is declared. The main difference between let and const is that variables declared with const are read-only, which means that their value cannot be reassigned.

const x = 5;
x = 10; // TypeError: Assignment to constant variable.

In this example, the variable x is declared with const and its value is set to 5. If you try to change the value of x, it will return a TypeError.

In summary, the main difference between variables created using var, let or const is the scope in which they are accessible and the ability to reassign their values. var variables are function scoped and can be accessed before they are declared, let variables are block-scoped and cannot be accessed before they are declared, and const variables are also block-scoped, cannot be accessed before they are declared and their value cannot be reassigned.

Additional resources
  • Frontend web development courses

    Beginner-friendly courses focusing on HTML, CSS, and JavaScript.

    View Courses
  • Frontend web development projects

    Beginner-friendly projects focusing on HTML, CSS, and JavaScript.

    View Projects
  • Free website templates

    Collection of free, high-quality website templates for your next project.

    View Templates