Hoisting problem

Hoisting problem
0.0 0

#1

I’m having difficulty understanding what hoisting is. Apparently this is an example of it:

var a = 2;

foo();                  // works because `foo()`
                        // declaration is "hoisted"

function foo() {
    a = 3;

    console.log( a );   // 3

    var a;              // declaration is "hoisted"
                        // to the top of `foo()`
}

console.log( a );   // 2
// Warning: It's not common or a good idea to rely on variable hoisting to use a variable earlier in its scope than its var decla

#2

you can format your code by wrapping it all in triple back-ticks. So …

To understand variable hoisting, first know that the code is “read” twice by the javascript engine. First pass does definitions, second pass does assignment.

So, for example, foo(); works because in the 1st pass the JS engine read through each line, scoping each variable (including the function foo() declaration). You can think of it like the engine rearranges your code during execution.


#3

@JamesMarcus Hoisting is when you call a function before it’s declared.

foo() // This line calls a function named foo before it's declared

The next line actually declares the function.

function foo() {
a = 3;

console.log( a );   // 3

var a;              // declaration is "hoisted"
                    // to the top of `foo()`
}

calling foo() before it’s declared in other languages doesn’t work. You would have to declare the function first then call it.


foo() {
//foo function is declared
//some code here

}

foo(); // foo function is called after it's declared

I think what they are trying to say is that when you call foo() at the top it should print 3 because the variable a inside the body of foo() is hoisted to the top.

This example is used to show that even though var a exists on the global scope calling foo() references var a inside the function.

Someone tell me if I’m wrong.

The same thing applies to variables.

console.log(a); //varialbe a is called before it's declared

var a = 100; // var a is declared and assigned a value

Again this works in Javascript but wouldn’t work in C++ or Java. I’m not sure if any other language allows hoisting.


#5

I cleaned up your code (I hope).
You need to use triple backticks to post code to the forum.
See this post for details.