Reputation: 556
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!
Upvotes: 0
Views: 102
Reputation: 707386
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);
}
Upvotes: 0
Reputation: 214969
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()
Upvotes: 1