Difference between var, let, and const in Javascript

Play this article

var, let, and const are three ways to declare variables in JavaScript. Here is a brief overview of each:

  • var: Variables declared var have function scope, meaning they are accessible within the function they are declared in. If a variable is declared var outside of a function, it has a global scope and can be accessed anywhere in the code. var declarations are hoisted, which means they are moved to the top of their scope and can be used before they are declared.

  • let: Variables declared let have block scope, meaning they are only accessible within the block they are declared in. This makes let a better choice for local variables within loops or other control structures. let declarations are also hoisted but cannot be accessed before they are declared.

  • const: Variables declared with const have block scope, just like let. The critical difference is that const variables cannot be reassigned after they are displayed. This makes const a good choice for declaring values that should not change, such as constant mathematical values or configuration settings.

In general, it is recommended to use const by default and only use let when you need to reassign the value of a variable. var should be used sparingly, as the behavior of function scope and hoisting can lead to unexpected results.

Thanks for reading :)