user1869935
user1869935

Reputation: 759

Why is this function yielding 'undefined'?

This is a very confusing behavior I came upon I cannot figure out:

var foo = 'outside';

function logIt(){

   console.log(foo); 
   var foo = 'inside';

} 

logIt();

That will yield undefined. Which is already unexplicable to me. But stranger is that this :

var foo = 'outside';

function logIt(){

   console.log(foo); 

} 

logIt();

Will actually yield outside.

Why is this happening?

Upvotes: 3

Views: 409

Answers (4)

Arsalan
Arsalan

Reputation: 471

As correctly mentioned by others, this is because of hoisting.

Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript. If a developer doesn't understand hoisting, programs may contain bugs (errors). To avoid bugs, always declare all variables at the beginning of every scope.

So in your example it should be like this:

function logIt(){ foo = 'inside'; console.log(foo); }

logIt();

for expected results.

Upvotes: 0

sandrina-p
sandrina-p

Reputation: 4160

You are looking to hoisting on javascript

When you write this:

var foo = 'outside';

function logIt(){

   console.log(foo); 
   var foo = 'inside';

} 

logIt();

The javascript will interpret the code like this:

var foo = 'outside';

function logIt(){
   var foo; //undefined
   console.log(foo); 
   foo = 'inside';

} 

logIt();

the foo inside logIt() is declared as undefined before console.log(foo), that's why it's undefined.

On the second example, the console.log(foo) runs after you declare the global var foo = 'outside', that's why it prints outside.

Upvotes: 0

DoXicK
DoXicK

Reputation: 4812

This has to do with hoisting variables in Javascript.

var foo = 'outside';

function logIt(){

   console.log(foo); 
   var foo = 'inside';
} 

logIt();

will internally become:

var foo = 'outside';

function logIt(){
   var foo;
   console.log(foo); 
   foo = 'inside';
} 

logIt();

and thus, foo will be undefined within the console.log :-)

Upvotes: 2

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

Variable hoisting

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top.

Hence your code is equivalent to:

var foo = 'outside';

function logIt(){
   var foo;
   console.log(foo); 
   foo = 'inside';
} 

logIt();

and at the time of the call to console.log, foo is undefined.

Upvotes: 5

Related Questions