javascript-declarar-variables-con-let

Creating Variables in JavaScript

  • 5 min

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;
Copied!

For example, like this

let message = 'Hello, World!';

console.log(message); // 'Hello, World!'
Copied!

In this example,

  • We have declared a variable called 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

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;
Copied!

For example,

let age = 25;
Copied!

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
Copied!

In this example,

  • We create a variable number with 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
}
Copied!

In this example,

  • The variable x is declared inside 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 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