When js encounters a Function: in that case what good are globals ?

Hello & Thanks ,
I purchased your book js101 today .And I dont understand this section:

When JavaScript encounters a function, one of the first things it does is scan the full body of the code for any declared variables. When it encounters them, it initializes them by default with a value of undefined. Because the doSomethingClever function is declaring a variable called foo, before the first alert even hits, an entry for foo is created with a value of undefined. Eventually, when our code hits var foo = “Good Bye!”, the value of foo is properly initialized. That doesn’t help our first alert function, but that does help the second one that follows the re-declaration of foo.
Chinnathambi, Kirupa (2014-08-01). JS101: JavaScript for Beginners (pp. 93-95). . Kindle Edition.

Please explain :
If that’s the case , what good are globals ?

That’s a great question! Take a look at the following code snippet:

var foo = "Hello!";

function doSomethingClever() {

    //var foo = "Good Bye!";

The value of foo is going to be Hello! The only reason you need to worry is if you are re-declaring a global variable somewhere inside your function. Other than that, global variables will work as expected.

Getting back to the bizarre situation described in the book, when that function is hit, the first thing that happens before any code executes is that all of the variables are figured out. This means that variables buried many lines below in your function get pushed to the top and initialized with a value of undefined. This case of a variable being pushed to top so that it is visible to everything in scope before it is actually used in our code is called variable hoisting.

To clarify this, the example in the book looks as follows to JavaScript:

var foo = "Hello!";

function doSomethingClever() {
    // foo got hoisted up here
    var foo = undefined;

    foo = "Good Bye!";

The easiest way to avoid this is to always declare your variables at the top of your function. That avoids any ambiguity about what a variable’s value is going to be.

Does that help? If not, let me know where I can elaborate further on.


1 Like