DEV Community

Karen Molina
Karen Molina

Posted on

Hoisting: Some exercises.


This time we will review the hoisting and the scope, one more time. Previously, we check them as concepts. But now, we going to realize come exercises to see how the hoisting and scope work inside the JS engine.

Remember in JS we have three ways to make a declaration: var, let and const.

console.log(variable) // undefined
var variable = "Hi";
console.log(variable) // Hi
Enter fullscreen mode Exit fullscreen mode

In this case, if we call the variable with the keyword "var" before the initialization, JS returns an undefined value. That's happened because, with the hoisting, anything variable with a "var" keyword has been moved at the top. So, JS moves the initialization, but not the value or the assignation. The value has been assigned in line 2.

What happens if we try to call our variables with the keywords "let" and "const" before the initialization?
Let's see below:


let variable2 = "Hi, i'm a let"
const anotherVariable = "Hi, i'm a const"

//ReferenceError: Cannot access anotherVariable' before initialization
//ReferenceError: Cannot access 'variable2' before initialization
Enter fullscreen mode Exit fullscreen mode

In this case, we see that JS gives us an error, a specific error called: Reference Error, that's means that JS does not hoist the declarations with those keywords.

Another issue with the hoisting happens in the functions. In this case, we must see some examples as to how the some of functions can be affected by the hoisting.

console.log(sum(2,3)) //5
function sum(num, num2) {
    return num + num2

console.log(sum2(2,3)) //ReferenceError: Cannot access 'sum2' before initialization
const sum2 = function(num1, num2) {
    return num1 + num2

console.log(sumNumbers(2,3)) // ReferenceError: Cannot access 'sumNumbers' before initialization
const sumNumbers = (num, num2) => num + num2
Enter fullscreen mode Exit fullscreen mode

In this case and always all the functions as function declaration have moved at the top like the variable with "var", but with a small and important difference, in this case, the function work. Why? The reason is that JS moves not just the initialization as a variable, JS moves the scope too. Meanwhile, a function expression and the arrow functions never will be moved at the top, and JS shows us a reference error if we invoke them before an initialization.

Top comments (0)