0

I'm learning Javascript at the minute and have a question about hoisting/scoping - perhaps I'm missing something.

If I define a global variable, I cant reference that variable's value inside a function because its out of scope?

var x = "hello";
function temp(){
 console.log(x);
}

turns out to be

var x = "hello";
function temp(){
 var x;
 console.log(x);
}

which both outputs undefined. What are the points of global variables or how do you use them inside a function? - As I said what am i missing here! :)

Also hoisting works on functions? But NOT on anonymous functions? Correct?

Any help is appreciated!

Thanks!

asked Oct 12, 2013 at 18:11
3

2 Answers 2

1

Hoisting only applies to local variables (those declared with var in the current scope). Since there's no var in temp(), there's no hoisting.

Here x will be hoisted:

var x = "hello";
function temp(){
 console.log(x); // undefined
 var x = 55
}
temp()

because this is interpreted as:

var x = "hello";
function temp(){
 var x /* = undefined */
 console.log(x);
 x = 55
}
temp()
answered Oct 12, 2013 at 18:15
Sign up to request clarification or add additional context in comments.

Comments

0

You can access any variable that is defined in your scope or higher. If that same variable name is redeclared within your scope, then that becomes a new variable definition that overrides the other one.

So, with this example:

var x = "hello";
function temp(){
 console.log(x); // outputs "hello" when temp() is called
}

x is defined at a higher scope than the function so it can be used inside the function.


In this example:

var x = "hello";
function temp(){
 var x;
 console.log(x); // outputs "undefined" when temp() is called
 // because local var x has not been assigned a value
}

You've defined a new variable x which is a local variable inside the function and it's value will be undefined until you assign it something.


The term "hoisting" means that a variable defined anywhere within a scope (e.g. within a function) behaves as if it was defined at the very beginning of the function no matter where the declaration actually appears.

So, because of hoisting, this example:

var x = 10;
function temp() {
 x = 3;
 y = 4;
 var x;
 console.log(x);
}

behaves like this and all references to x within the function are to the local version of x:

var x = 10;
function temp() {
 var x;
 x = 3;
 y = 4;
 console.log(x);
}
answered Oct 12, 2013 at 18:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.