In JavaScript programs, values can appear as literals or be stored in variables. Think of variables as containers for values. To use a variable, it must first be declared. JavaScript offers several ways to declare variables, each with its own behavior and scope rules.
The var keyword declares a variable in the function or global scope:
var name = "Kyle";
var age;Variables declared with var are accessible throughout the function or file, even outside of blocks like if.
let is similar to var but introduces block scope, meaning the variable is only accessible within the block it’s declared in:
var adult = true;
if (adult) {
var name = "Kyle";
let age = 39;
console.log("Shhh, this is a secret!");
}
console.log(name); // Kyle
console.log(age); // Error!age is block-scoped to the if block, while name is not.
Using let helps limit the visibility of variables, reducing the risk of name collisions. var is still useful when broader access is needed. Choosing between them depends on the context.
const is like let but with an added restriction: it must be initialized at declaration and cannot be reassigned:
const myBirthday = true;
let age = 39;
if (myBirthday) {
age = age + 1; // OK
myBirthday = false; // Error!
}const prevents reassignment but not mutation. Using const with objects can be misleading:
const actors = ["Morgan Freeman", "Jennifer Aniston"];
actors[2] = "Tom Cruise"; // Allowed :(
actors = []; // Error!The best use of const is for simple primitive values with meaningful names, like myBirthday instead of true.
If you use const only for primitive values, you avoid confusion between reassignment (disallowed) and mutation (allowed). This is the safest way to use const.
Functions also declare variables. Parameters behave like internal variables:
function hello(name) {
console.log(`Hello, ${name}.`);
}
hello("Kyle"); // Hello, Kylehello is declared in the outer scope, while name is scoped to the function body.
Variables can also be declared in catch clauses. These are block-scoped, similar to let:
try {
someError();
}
catch (err) {
console.log(err);
}err exists only within the catch block.
JavaScript variables can be declared using var, let, or const, each with distinct scope and mutability rules. Understanding these differences helps you write cleaner, more reliable code. Variables can also be declared in functions and catch blocks, making scope awareness essential for maintainable programming.