The difference between "let", "const" and "var" in Javascript

In JavaScript, "let", "const" and "var" are keywords used to declare variables, but they have slightly different behaviors. Here are the main differences between them.

Block Scope

"var": Has function scope. This means that the variable declared with "var" is visible throughout the function where it was declared, regardless of blocks.

"let" and "const": Have block scope. This means that the variable is only visible within the block where it was declared.

function example() {
   if (true) {
     var x = 10; // visible throughout the function
     let y = 20; // visible only inside this block
     const z = 30; // visible only inside this block
   }
   console.log(x); // it works
   console.log(y); // error: y is not defined
   console.log(z); // error: z is not defined
}

Hoisting

"var": Is hoisted, which means the variable declaration is moved to the top of the scope. However, the boot remains in its original location.

"let" and "const": They also suffer from hoisting, but unlike "var", these variables are not initialized until execution reaches the line of code where they were declared.

console.log(a); // undefined
var a = 5;

console.log(b); // error: b is not defined
let b = 10;


Reassignment and Mutability

"var" and "let": Allow reassignment, that is, the value of the variable can be changed.

"const": Does not allow reassignment. However, this does not prevent the mutability of objects and arrays declared with "const".

var variableVar = 1;
let variableLet = 2;
const constant = 3;

variableVar = 4; // It works
variableLet = 5; // It works
// constant = 6; // Error: cannot reassign a constant

const object = { key: 'value' };
object.key = 'new value'; // works, even with const

In summary, when programming in modern JavaScript, it is recommended to prefer "let" and "const" over "var" as let provides block scope and const helps prevent accidental reassignment. Use "const" whenever possible to create immutable variables.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....