let vs var vs Const

kamesh - Jun 2 - - Dev Community

Let’s dive into the differences between var, let, and const in JavaScript. These three keywords are used for variable declaration, but they behave differently. Here’s a breakdown:

var:

Scope: Variables declared with var are either globally scoped or function/locally scoped.
Globally scoped: If a var variable is declared outside a function, it’s available for use throughout the entire window.
Function scoped: If declared within a function, it’s accessible only within that function.
Hoisting: var variables are hoisted to the top of their scope and initialized with a value of undefined.
Re-declaration and Updates: You can re-declare and update var variables within the same scope without errors.

var greeter = "hey hi";
var times = 4;
if (times > 3) {
    var greeter = "say Hello instead";
}
// greeter is now "say Hello instead"

Enter fullscreen mode Exit fullscreen mode

let:

Scope: Variables declared with let have block-level scope. They’re limited to the block they’re declared in (e.g., within loops or conditionals).
Hoisting: Like var, let variables are hoisted but not initialized until the actual declaration.
Reassignment: You can reassign let variables, making them useful when you need to change a value over time.

let greeting = "hello";
if (true) {
    let greeting = "hi"; // Different scope
}
// greeting is still "hello"

Enter fullscreen mode Exit fullscreen mode

const:

Scope: Like let, const also has block-level scope.
Reassignment: Variables declared with const cannot be reassigned after their initial assignment.
Use Case: Use const for values that should remain constant (e.g., mathematical constants, configuration settings).

const pi = 3.14;
// pi cannot be reassigned

Enter fullscreen mode Exit fullscreen mode

Advantage: It improves code readability by clearly indicating immutability.

In summary:

Use let when you need to reassign variables within a block.
Use const for constants that shouldn’t change.
Minimize the use of var due to its function scope and potential issues

. . .