Wednesday, January 2, 2013

Short JavaScript Quiz

Give the output of  the following and define the scope of variables

<script>


// a _____-scoped variable
var a=1;

// ______ scope
function one(){
    alert(a); 
}

// ______ scope
function two(a){
    alert(a);
}

// ______ scope
function three(){
  var a = 3;
  alert(a);
}

// Intermediate: 
Does javascript have a block scope ?
function four(){
    if(true){
        var a=4;
    }

    alert(a);
}


// Intermediate:  ______ ______ properties
function Five(){
    this.a = 5;
}


// Advanced: closure
var six = function(){
    var foo = 6;

    return function(){
        // javascript - "closure" means I have access to foo in here,
        // [ to be updated ]
        alert(foo);
    }
}()


// Advanced: __________ scope resolution
function Seven(){
  this.a = 7;
}

// [object].______ loses to [object].______ in the scope chain
Seven.prototype.a = -1; // ______ get reached, because __ is __ in the constructor above.
Seven.prototype.b = 8; // ______ get reached, even though __ is ___ set in the constructor.


one();
two(2);
three();
four();
alert(new Five().a);
six();
alert(new Seven().a);
alert(new Seven().b);


</script>
The best ever examples given by Triptych - on Stackoverflow.com
Source:
http://stackoverflow.com/questions/500431/javascript-variable-scope

1 comment:

  1. // a global-scoped variable
    var a=1;

    // global scope
    function one(){
    alert(a);
    }

    // Local scope
    function two(a){
    alert(a);
    }

    // Local scope
    function three(){
    var a = 3;
    alert(a);
    }

    // Intermediate:
    Is there a block scope in javascript ? - No
    function four(){
    if(true){
    var a=4;
    }

    alert(a); // alerts '4', not the global value of '1'
    }


    // Intermediate: Closure - Object properties
    function Five(){
    this.a = 5;
    }


    // Advanced: closure
    var six = function(){
    var foo = 6;

    return function(){
    // javascript - "closure" means I have access to foo in here,
    // [ to be updated ]
    alert(foo);
    }
    }()


    // Advanced: Prototype scope resolution
    function Seven(){
    this.a = 7;
    }

    // [object].prototype.property loses to [object].property in the scope chain

    Seven.prototype.a = -1; // Will not get reached, because a is set in the constructor above.

    Seven.prototype.b = 8; // Will get reached, even though b is not set in the constructor.

    o/p
    one(); 1
    two(2); 2
    three(); 3
    four(); 4
    alert(new Five().a); 5
    six(); 6
    alert(new Seven().a); 7
    alert(new Seven().b); 8

    ReplyDelete