For the More Curious: Hoisting

JavaScript was created so that nonprofessional programmers could create web content with some basic interactivity. Although the language has features intended to make code error-resistant, some of its features end up causing errors in practice. One of these features is hoisting.

When the JavaScript engine interprets your code, it finds all of the variable and function declarations and moves them to the top of the function they are in. (Or, if they are not in a function, they are evaluated before the rest of the code.)

This is best illustrated with an example. When you write this code:

function logSomeValues () {
  console.log(myVal);
  var myVal = 5;
  console.log(myVal);
}

it is interpreted as though you had written:

function logSomeValues () {
  var myVal;
  console.log(myVal);
  myVal = 5;
  console.log(myVal);
}

If you called logSomeValues the console, you would see this:

> logSomeValues();
undefined
5

Notice that it is only the declaration that is hoisted. The assignment stays in place. Naturally, this can cause confusion, especially if you were to try to declare variables in an if statement or inside of a loop. In other languages, the curly braces denote a block, which has its own scope. In JavaScript, curly brace blocks do not create scope. Only functions create scope.

Take a look at another example:

var myVal =  11;
function doNotWriteCodeLikeThis() {
  if (myVal > 10) {
    var myVal = 0;
    console.log('myVal was greater than 10; resetting to 0');
  } else {
    console.log('no need to reset.');
  }
  return myVal;
}

You might expect that 'myVal was greater than 10; resetting to 0' would be printed to the console and the value 0 returned. Instead, this is what would be printed:

> doNotWriteCodeLikeThis();
no need to reset.
undefined

The declaration var myVal is moved to the top of the function, so before the if clause is evaluated, myVal has a value of undefined. The assignment stays inside the if block.

Function declarations are also hoisted, but in their entirety. That means that this works just fine:

boo();

// Declare after calling:
function boo() {
  console.log('BOO!!');
}

JavaScript moves the entire function declaration block to the top, allowing the invocation of boo to happen without any problems:

> boo();
BOO!!

let statements are immune to hoisting. const statements, which let you declare variables that cannot be reassigned, are also immune.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.186.178