DEV Community

sromelrey
sromelrey

Posted on

Understanding JavaScript keyword var, let, const and hoisting.

Good day, everyone! Today, we'll explore how var, let, and const work and how hoisting affects each.

Before we dive in, I recommend reading my blog on execution context for a deeper understanding of hoisting.
JavaScript Execution Context and JS Engine Components

Goals and Objectives in this topic:

  • Understand how var, let, and const works under the hood.
  • How hoisting affects each keyword.
  • What is Temporal Dead Zone ?

The keyword var, let, and const is what we use when declaring a variable in JavaScript.

Let's start with the var keyword before ES6 declaring variable can only be done using var the following are the features of this keyword:

var keyword:

  • Function Scope: Variables declared with var are scoped to the function in which they are declared.

  • Hoisting: Variables are hoisted to the top of their scope and initialized with undefined.

  • Re-declaration: The same variable can be declared multiple times within the same scope without causing an error.

  • Global Object Property: If declared outside a function, var becomes a property of the global object (e.g., window in browsers).

The 'let' and 'const' keywords are features introduced in ES6, addressing the shortcomings of the 'var' keyword.
Here's a list of how and what you can use this keywords:

let keyword:

  • Block Scope: Variables declared with let are scoped to the block in which they are declared (e.g., inside a {}).

  • Hoisting: Variables are hoisted but not initialized, leading to a temporal dead zone until the declaration is encountered.

  • Re-declaration: Cannot be re-declared within the same scope, preventing accidental redefinitions.

  • Temporal Dead Zone: Accessing the variable before its declaration results in a Reference Error.

const keyword:

  • Block Scope: Variables declared with const are scoped to the block in which they are declared.

  • Hoisting: Variables are hoisted but not initialized, leading to a temporal dead zone until the declaration is encountered.

  • Re-declaration: Cannot be re-declared within the same scope, similar to let.

  • Immutability: Must be initialized at the time of declaration and cannot be reassigned. However, if the variable holds an object, the object's properties can still be modified.

  • Temporal Dead Zone: Accessing the variable before its declaration results in a Reference Error.

Understanding how hoisting works with different keywords

What is hoisting? Hoisting is a feature in JavaScript that allows you to use variables or invoke functions before they are declared. Here's a sample code to illustrate this concept:

Here's a sample code of hoisting using var and function declaration
// * Accessing the 'age' variable before it is initialized
console.log(age);
// ? Will log undefined

var age = 12;

// * Invoking the 'logAge' function before it is declared
logAge(age);
// ? Will log AGE is 12

// * Invoking logAge Function Declaration before it's being declare
function logAge(ageArg) {
  console.log(`log AGE is ${ageArg}`);
}
Enter fullscreen mode Exit fullscreen mode
Here's a sample code of hoisting using let and const and function expression
// * Accessing let age before it's initialization
console.log(age);

let age = 12;

// * Invoking logAge Function Expression before it's being declare
logAge(age);

let logAge = function () {
  console.log(`log AGE is ${ageArg}`);
};
Enter fullscreen mode Exit fullscreen mode

I will write a separate blog post under the topic of functions to further explain how hoisting works with function expressions and function declarations when invoking a function.

Temporal Dead Zone

The temporal dead zone starts from the block until the let or const variable declaration is processed. In other words, it is the location where you cannot access the let variables before they are defined.

Here's a sample code to demonstrate the TDZ

console.log(myVar); // ReferenceError: Cannot access 'myVar' before initialization
let myVar = 10;
console.log(myVar); // Output: 10
Enter fullscreen mode Exit fullscreen mode

Although 'let' and 'const' are hoisted, accessing them before their declaration results in a Reference Error, unlike 'var' which returns undefined. This behavior is known as the 'temporal dead zone."

Conclusion

Understanding how var, let, and const work and how hoisting affects each keyword is crucial for writing efficient JavaScript code.

  • var is function-scoped, hoisted, and can be re-declared within the same scope, which can lead to unexpected behaviors.
  • let and const are block-scoped, also hoisted but not initialized until their declaration, leading to the temporal dead zone which prevents access before initialization.
  • const also enforces immutability, meaning it must be initialized during declaration and cannot be reassigned.

Hoisting allows functions and variables to be used before they are declared, but understanding the nuances between these keywords helps prevent common pitfalls, such as reference errors or unintended variable reassignments. For more details on hoisting with function expressions and declarations, stay tuned for my upcoming blog post.

Thanks for reading 😁😁😁😁

Top comments (0)