Language: EN

javascript-declarar-variables-con-let

Creating Variables in JavaScript

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).

Before ES6, variables were declared with var. This syntax is deprecated 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 named message
  • We have assigned it the value 'Hello, World!'
  • Then, we use console.log to print the value of message

let does not allow declaring the same variable more than once in the same scope (which helps avoid redeclaration errors)

Variable Initialization

The initialization of a variable is the process of assigning it an initial value at the time 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 named 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 created a variable number with the value 42
  • We changed 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 x is declared within the if block
  • Therefore, it is only accessible within that block
  • If we try to access x outside the block, it results in a reference error (ReferenceError)

Hoisting and TDZ

In JavaScript, variable and function declarations are “hoisted” to the beginning of their execution context.

However, declared variables are not fully available until their definition. This is referred to as being in the TDZ (temporal dead zone).

Does all this seem really weird to you? Don’t worry, you’re not the only one. This is due to the huge mistake … I mean… the monumental blunder JavaScript made in its early versions with var.

Let’s see it very simply with some examples 👇

What happens if we access a variable that is not declared?

If you try to access a variable that has never been declared within its scope, like:

function example() {
	console.log(a); // ReferenceError: a is not defined
}

JavaScript generates a ReferenceError, with the message a is not defined.

This means that the JavaScript engine cannot find the variable in the current scope or any upper scope (meaning it has no idea what you’re talking about).

What happens if we access a variable in the TDZ?

However, let’s see what happens if we try to access a variable that is declared in the body, but before its declaration (that is, it is in its TDZ). For example like this:

function hoistingExample() {
    console.log(a); // ReferenceError: Cannot access 'a' before initialization
    let a = 5;
}

Now we will get a different error Cannot access ‘a’ before initialization. This means the JavaScript engine does know that a exists, but it won’t let you touch it.

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);