Javascript Basic Topics you need to know #1 ( Scope, Hoisting, Temporal Dead Zone)
Tags: javascript, programming, beginners
Published: 2023-03-16 04:17:16

Have you ever felt like your Javascript code was doing weird things, or you didn't understand why you have a undefined variable? and you made sure to initialize and assign a value to this variable?
Well, in reality there is nothing strange, we just forget or do not know some basic and easy principles that I will show below so that you do not forget them again.

Scope, Hoisting and Temporal Dead Zone that's what this post is about

#Scope

**What is?**

The scope determines the accessibility of the variables in each part of our code.

In Javascript we have different types of Scopes:

**Global Scope**

A Variable is said to be in global scope when it is declared outside of a function or block. We will be able to access these types of variables from any part of our code, whether inside or outside a function.

```

var name = "Leonardo";
// The code written in this part will be able to access name.

function myFunction() {
  // The code written in this part will also be able to 
     access name.
}
```
**Local Scope**

The variables that we define inside a function are local variables, that is, they are found in the local Scope. This means that these types of variables will only live within the function where we have declared them and if we try to access them outside of it, these variables will not be defined.

```
// The code written in this part will NOT be able to access the variable name.

function myFunction() {
  var name = "Leonardo";
  // The code written here can access to the variable.
}
```

**Block Scope**

Unlike the local scope, this scope is limited to the block of code where the variable was defined. Since ECMAScript 6 we have the let and const keywords which allow us to have a block scope, this means that the variables will only live within the corresponding code block.

```
if (true) {
    // this if block does not create a scope
    // variable name is global because of the use of the 'var' keyword
    var name = 'Leonardo';
    // country is in the local scope because of the use of the 'let' keyword
    let country = 'Mexico';
    // language is also a local scope because of the use of the 'const' keyword
    const language = 'Javascript';
}
console.log(name); // prints 'Leonardo'
console.log(country); // Uncaught ReferenceError: country is not defined
console. log(language); // Uncaught ReferenceError: language is not defined
```

**Lexical Scope**

The lexical scope means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope. This means that child functions are lexically linked to the execution context of their parents.

```
function myFunction() {
    var name = 'Leonardo';
    // we can't access language from here
    function parent() {
        // name is accessible from here.
        // language is not accessible.
        function child() {
            // We can also access name from here.
            var language = 'Javascript';
        }
    }
}
```

#Hoisting

**What is?**

Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the beginning of the code, but this is not actually the case. 

What happens is that the declarations of variables and functions are allocated in memory during the compilation phase, but they remain exactly where you have written them in the code.

**Example of hoisting with function**

```
hello("Leo");

function hello(name) {
  console.log("Hello " + name);
}

/*
Printed Result "Hello Leo"
*/

```
One of the advantages in JavaScript of hoisting is that it allows you to use a function before declaring it in your code.

As you can see, even though we call the function in the code first, before it is written, the code still works.


#Temporal Dead Zone

**What is?**

A temporal dead zone (TDZ) is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value.

Suppose you attempt to access a variable before its complete initialization. In such a case, JavaScript will throw a `ReferenceError`.

So, to prevent JavaScript from throwing such an error, you've got to remember to access your variables from outside the temporal dead zone.

But where exactly does TDZ(Temporal Dead Zone) begin and end?

```
// TDZ start here
console.log(name); // returns ReferenceError because name TDZ are present
let name = "Leonardo" // TDZ ends 
// TDZ not exist here
```
Here is how you can access `name` successfully after its complete initialization:

```
  let name = "Leonardo"; // name TDZ ends here
  console.log(name); // returns "Leonardo" because name TDZ does not exist here
```

All temporal dead zone principles of let variables apply also to const. However, var works differently.

The main difference between the temporal dead zone of a var, let, and const variable is when their TDZ ends.

```
// name TDZ starts and ends here
  console.log(name); // returns undefined because name TDZ does not exist here
  var name = "Leonardo"; // name TDZ does not exist here
  console.log(name); // returns "Leonardo" because name TDZ does not exist here
```
The console.log statement successfully returned a value (undefined) because JavaScript automatically assigns undefined to a hoisted var variable.

In other words, when Javascript hoists a var variable, it automatically initializes the variable with the value undefined.

In contrast, JavaScript does not initialize a let (or const) variable with any value whenever it hoists the variable. Instead, the variable remains dead and inaccessible.

Therefore, a let (or const) variable's TDZ ends when JavaScript fully initializes it with the value specified during its declaration.

However, a var variable's TDZ ends immediately after its hoisting , not when the variable gets fully initialized with the value specified during its declaration.

**Conclusions**

These are basic concepts that many of us are unaware of because we start programming without taking a look at how the language works and we go straight to throwing code, but knowing how the language works and knowing these basic concepts will make us better developers to generate best solutions.