All mock tests are FREE till 31 December — register to save your progress

Consider the JavaScript code:

var y = "12";
function f() {
    var y = "6";
    alert(this.y);
    function g() { alert(y); }
    g();
}
f();

If M is the number of alert dialog boxes generated by this code and D1, D2, …, DM are the contents displayed in each, then:

Pick an option to check yourself, or open the answer below.

Show answer & explanation

Correct answer: D. M=2; D1 displays ”12”; D2 displays ”6”

Explanation

f() is called as a plain function, so this is the global object and this.y is "12". g() reads the closest y in scope, f's local "6". Two alerts: "12" then "6".

More Programming Languages and Computer Graphics questions