let and const
While the var keyword is part of JavaScript’s legacy, modern development overwhelmingly favors two newer keywords introduced in ES6 (ECMAScript 2015): let and const.
Understanding let and const
let: Used for declaring variables that can be reassigned a new value later.const: Used for declaring variables that cannot be reassigned. They are constant.
A general rule of thumb is to default to using const for any value you do not intend to change. If you know a variable’s value needs to be updated during execution, use let. This practice helps prevent accidental reassignments and makes your code’s intent clearer.
// A username might change if someone logs into a different account
let username = "dengar_the_bh";
username = "boba_fett";
// A hard limit shouldn't change during runtime
const limit = 1000;
Scoping Differences
One of the most significant reasons to use let and const over var is how they are scoped.
varis function-scoped: If you declare avarinside anifblock or aforloop, that variable “leaks” out and is accessible outside of that block.letandconstare block-scoped: They are confined to the block (defined by{}) in which they are declared, preventing unintended behavior and variable collisions.
Practical Example
Using block-scoped variables prevents temporary block variables from unintentionally overwriting outer variables.
const isBirthday = true;
let messageText = "Welcome!";
if (isBirthday) {
// This block-scoped variable does not overwrite the outer messageText
const birthdayMessage = "Happy Birthday!";
console.log("Sending birthday message...");
console.log("Message:", birthdayMessage);
}
console.log("Sending welcome message...");
console.log("Message:", messageText);