In JavaScript, variables are data containers that allow us to store and manipulate values throughout the execution of a program.
In JavaScript, variables are declared with the reserved word let, which was introduced in ECMAScript 6 (2015).
If you want to learn more, check out the Introduction to Programming Course
Before ES6, variables were declared with var. This syntax is obsolete and you should not use it. More information in its own article.
Variable Declaration
To declare a variable, simply use the keyword let followed by the variable name (and optionally, an initial assignment).
The basic syntax for declaring a variable using let is as follows:
let variableName;
For example, like this
let message = 'Hello, World!';
console.log(message); // 'Hello, World!'
In this example,
- We have declared a variable called
message - We have assigned it the value
'Hello, World!' - Then, we use
console.logto print the value ofmessage
let does not allow declaring the same variable more than once in the same scope (which helps avoid redeclaration errors)
Variable Initialization
Variable initialization is the process of assigning an initial value at the moment of its declaration. This can be done simultaneously with the declaration using the following syntax:
let variableName = value;
For example,
let age = 25;
In this example,
- We have declared a variable called
age - We have assigned it the value
25
Variable Modification
Declared variables can be reassigned after their initialization. This means we can change the value stored in a variable.
let number = 42;
console.log(number); // 42
number = 100;
console.log(number); // 100
In this example,
- We create a variable
numberwith value 42 - We change the value of the variable to
100
Block Scope
In JavaScript, variables defined with let have block scope. This means that a variable declared with let is only accessible within the block {} in which it is declared.
function blockExample() {
if (true) {
let x = 10;
console.log(x); // ✅ 10
}
console.log(x); // ❌ ReferenceError: x is not defined
}
In this example,
- The variable
xis declared inside theifblock - Therefore, it is only accessible within that block
- If we try to access
xoutside the block, it results in a reference error (ReferenceError)
Hoisting and TDZ
In JavaScript, variable and function declarations are “hoisted” to the top of their execution context.
However, declared variables are not fully available until their definition. We call this being in the TDZ (temporal dead zone).
Does all this seem very weird to you? Don’t worry, you’re not the only one. This is due to the huge blunder … I mean… the monumental mistake JavaScript made in its early versions with var.
Let’s see it very simply with some examples 👇
Practical Examples
Iteration Counter
for (let i = 0; i < 10; i++) {
console.log(i);
}
// i is not defined outside the for block
console.log(i); // Error: i is not defined
Filtering Elements in an Array
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6, 8, 10]
Event Handling
let buttons = document.querySelectorAll("button");
buttons.forEach((button, index) => {
button.addEventListener("click", () => {
console.log(`Button ${index} clicked`);
});
});
Handling Asynchronous Data
async function fetchData(url) {
let response = await fetch(url);
let data = await response.json();
console.log(data);
}
let url = "https://api.example.com/data";
fetchData(url);
