Using var in Javascript

So a little bit of history 101 when it comes to the ‘var’ keyword in Javascript. Back when Javascript was super weird, I mean Javascript is still weird don’t get me wrong. For this reason I started liking Javascript – I used to think it was just to messy of a language to write in. I had some major trust issues with it, my relationship with PHP was far better. Alright enough with relationships, let’s dive right in.

Again, all credit goes to Tech Sith for making this all possible. I just seem to be on a roll on this Javascript series so why not finish it you know.

Function Scope

Javascript eats, sleeps and breathes functions – it’s all over the place. It’s important to understand that the ‘var’ keyword is so interrelated to functions in javascript. This sets Javascript apart from other languages in how functions are composed and where variable’s are lexically declared.

Below is a great example of how Javascript variables are functionally scoped.


var x = function() {


        if (true) {
                // this should not be available
                // outside this if block
                var y = 1; 
        }

        console.log(y); // but it is available!

}

x(); // Output is 1

Lexical Scoping

This basically means that variables declared outside a function are available inside inside another function. Check out the below example, we moved a few things around a bit.


var x = function() {
        // this variable is available everywhere 
        // within this function
        var y = 1;

        var z = function() {
                // y is available here too!
                console.log(y);
        }

        z();


}

x(); // Outputs 1

Hoisting and Scope – Interview Question

To end this post, I’m going provide a tricky scenario that’s mostly to come up in a Javascript interview. A simple yet fundamental example that can throw any developer off his/her game.


// 
var y = 2;
  
var x = function() {

        // this will look for y
        // but the closest variable 
        // is right underneath it
        // but... it's defined after calling it
        console.log(y);

        // this function will ignore
        // y variable sitting outside 
        var y = 1;


}

x(); // Output is undefined

That was a little tricky. I’ll admit this got me the first time and hey if you got it wrong too, there’s nothing to be ashamed of. I expected the output would be “2”, but since Javascript operates by going down a “scope chain” – it first tries to call the nearest variable lexically. However in this case, the variable is defined after it’s called so this would result in undefined.

In closing, understanding super simple fundamental concepts like this can really improve your program, enforce clean code and eliminate any confusion. Stay tuned for more advanced Javascript topics. I’m really excited to cover “function currying” in my next post! Keep immersing!