Hoisting

This is another thing that Java developers usually easily get confused. Hoisting is a metaphor for the way that JavaScript interpreters will lift function declarations and variable declarations to the top of their containing scope. So, In JavaScript, you can see something that is obviously wrong and will definitely break the compilation if you write that in Java, but it is totally valid in JavaScript.

Let’s see an example:

1. travel = 'No plan';
2. var travel;
3. console.log(travel); // Is the output: undefined?
4.
5. function travel() {
6. console.log('Traveling');
7. }
8. travel(); // Is the output: Traveling?

What will the output be when the JavaScript engine executes line 3 and 8? It is not undefined, and not Traveling. Line 3 is "No plan" and line 8 is "Uncaught TypeError".

Here is what the JavaScript interpreter sees when it processes the preceding code:

1.  // Function declaration moved to the top of the scope
2. function travel() {
3. console.log('Traveling');
4. }
5. // Variable declaration moved under function declaration
6. var travel;
7. travel = 'No plan';
8.
9. console.log(travel); // No plan
10. travel(); // Uncaught TypeError: travel is not a function

JavaScript interpreter moves the function declarations up to the top, followed by variables declarations. Function expressions, for example, var travel = function(){}, are not lifted to the top as function declarations because they are also variable declarations.

Let's see another example:

1.  function workout() { 
2. goToGym(); // What will the output be?
3. var goToGym = function () {
4. console.log('Workout in Gym A');
5. }
6. return;
7. function goToGym() {
8. console.log('Workout in Gym B');
9. }
10. }
11. workout();

What will the output be when line 2 is executed? It is "Workout in Gym B.". And here is what the interpreter sees when it processes the code:

1.  function workout() {
2. function goToGym() {
3. console.log('Workout in Gym B');
4. }
5. var goToGym;
6. goToGym();
7. goToGym = function () {
8. console.log('Workout in Gym A');
9. }
10. return;
11. }
12. workout();

The interpreter moves the function declaration to the top of the scope and then the variable declaration, but not the assignment. So when goToGym() is executed, the assignment expression to the new function hasn't happened yet.

To wrap up, before executing, JavaScript interpreters will move the function declarations, and then variable declarations, without assignment expressions, up to the top of the containing scope. And it is valid to put function declarations after the return statement.

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

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