Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is the scope of variables in JavaScript?

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 96
    Comment on it

    Scope is the set of variables, objects that you have access to.

    Here are some examples that will explain you about scopes :-

    1.A globally-scoped variable

        var a = 1;
    
        // global scope
        function one() {
         console.log(a);
        }
    

    This variable can be accessed anywhere.

    2.Local scope

        function three() {
          var a = 3;
          console.log(a);
        }
    

    This variable can only be accessed inside this function.

    3.Intermediate

    var a = 2;
    
        function four() {
          if (true) {
            var a = 5;
          }
    
          console.log(a); // alerts '5', not the global value of '2'
        }
    

    This will give value of a as '5', not '2'.

    4.Intermediate: Object properties

        var a = 1;
    
        function five() {
          this.a = 5;
        }
    
    This function will use '5' as a's value, while elsewhere a will have '1' value.

    5.Global+Local: An extra complex Case

        var a = 2;
    
        (function () {
            console.log(a);
            var a = 12;
            console.log(a); 
        });
    

    This function will give output as undefined and 12 rather than 2 and 12 since JavaScript always moves variable declarations (not initializations) to the top of the scope.

    I hope these examples will give you a better insight of scopes in JavaScript.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: