Why is this function yielding 'undefined'?

function, javascript, scope, var

Solution

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`.

Problem

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?

Original source

Related problems