Appearance
Variables
Modern JavaScript offers several ways to declare variables, each with different rules about scope and reassignment. Understanding these differences is crucial for writing predictable and maintainable code.
Declaring
JavaScript provides three ways to declare variables: let, const, and var.
let: Declares variables limited to the block, statement, or expression where they are used. Variables declared with let can be reassigned.
js
let x = 10;
x = 20; // Reassignment is allowed
console.log(x); // 20
if (x > 5) {
let y = 100; // y is only accessible in this block
console.log(y); // 100
}
// console.log(y); // Error: y is not defined (out of scope)const: Declare variables that are not meant to be reassigned. However, it does not make the object it refers to immutable.
js
const x = 10;
// x = 20; // Error: Assignment to constant variable
if (x > 5) {
const y = 100; // y is only accessible in this block
console.log(y); // 100
}
// console.log(y); // Error: y is not defined (out of scope)var: Has function scope and is hoisted to the top of its scope. Due to its unintuitive non-block scope behaviour, it's generally advisable to avoid it. var was the only way to define variables in early JavaScript standards, you might see it in older examples or codebases.
js
var x = 10;
x = 20; // Reassignment is allowed
console.log(x); // 20
if (x > 5) {
var y = 100; // y is accessible OUTSIDE this block!
console.log(y); // 100
}
console.log(y); // 100 - Notice y is still accessible!🛑 We won't use
varin CS 349 and neither should you.
External Resources