Why is scope concept not working here , kindly guide

Hi,
I was going through an exercise online and was once again stumped by a simple logic in terms of how to decide scope in JS …

var foo = "bar";

function bar() {
console.log(foo);
 var foo = "baz";
}

bar()

Now here the output is --> undefined

Why is that so , if i remove and make the code like below

var foo = "bar";

function bar() {
console.log(foo);

}

bar()

The output is -----> bar

Why does i get undefined even though i have declared var foo = “baz” in the first case, why it can’t just look one line below in its scope of function and give the result

rather it gives undefined , if can afford to look outside of function scope why not just look one line below in same function scope …

I am totally confused , am i not thinking properly or its the way JS is …Thanks

The first snippet prints undefined because at the point where console.log runs, the foo variable in the bar function is still yet to be assigned a value. It can’t just “look at the next line” to see foo's value.

@kevcomedia - thanks, so you mean to suggest we need to go line by line , and hence in every case where is value is declared in a particular scope after it being used will give undefined …

function bar() {

 var foo = "baz";

console.log(foo);
}

like in above code it works , so in any scope if the variable is declared below its use, it will give undefined and also not look out of its scope ? Kindly guide …

The code you posted is what the code will look like after the variable declarations have been hoisted at the top… well, almost. Only the declaration itself is hoisted, not the assignment.

It actually looks like this:

function bar() {
  // the declaration is hoisted; the assignment is left where it is
  var foo;

  console.log(foo); // `foo` is still undefined at this point.
  foo = 'baz';
}

@kevcomedia - thanks, that is wonderfully explained , now i get it , but just one last query just if you wish to answer, what is the benefit of doing like this ?

What do you mean? By writing code like I did? I don’t think you’ll actually write code like that, since usually you’d place variable assignments before they’re used anyway. It’s just a demonstration of how JS works with variable declarations.

I don’t know if I answered your question. Please clarify if I didn’t.

@kevcomedia - no i understand one does not write code like you explained, i was just asking why JS which claims to be compiled language as suggested by kyle simpson as well as crockford, two famous authors on JS …

What is the point of restricting itself from looking down in the same scope for a variable value and print it , rather then print undefined … Thanks

As far as I can tell, most languages execute lines from top to bottom. Though the variable is indeed in scope, it so happens that the console.log line runs before the variable is assigned a meaningful value. I don’t think there’s any more to it other than the ordering of the lines.

1 Like