Category Archives: Javascript

Today is Tuesday September 26, 2017
  • users

    JavaScript variable scope

    Most of you who are in development will be aware of JavaScript variable scoping. All the JavaScript  code which are loaded from various files are usually executed

    at a common global space, which is window in case of browser.

    You can restrict the scope of a variable using function, as how in the code below.

    var x = 1

    var TZT = function (a) {

        var y = 2;

    }

    Where the variable x as an window level scope and variable y is available within the function TZT only

    An interesting bug or peculiarity in JavaScript is a variable becomes part of global scope when it is declared without the var keyword as shown below.

    var x = 1

    var TZT = function (a) {

         y = 2;

    }

    In the above code y is accessible globally. This will cause lot of unexpected result since they can override a global variable already in existence.

    To give a measure of importance of it, I wrote a small code which collects all the global variables and based on which we have around 812 global variables at the point when the user logs in (inclusive of inbuilt variable and  third party scripts),which might increase when someone declares window level  variables.

    Since we have a single page application model for talent Oz this becomes even more important since all the variables reside in the scope at all point of time. So it’s better if we have one common global namespace for talentoz related code and be careful when you are declaring a variable.

    If you want to check a  variable already exists in global namespace then call the following function in browser address bar , before creating it.

     Javascript:TZT(‘variablename’);