var value = 1;
function execute()
{
console.log(value);
var value = 2;
console.log(this.value);
this.value = 3;
}
// What will these two statements print to the console?
execute();
var instance = new execute();
Let's analyze this JavaScript interview question step by step.
1. execute() call outputs: *undefined* , *1*
a. The first print statement outputs undefined due to JavaScript's hoisting mechanism. In JavaScript, function and variable declarations are hoisted to the top of their scope during the compilation phase. Let's examine how this works with an example:
test(); // This will execute correctly
function test()
{
alert("executed");
}
Although the function call appears before its declaration, it works because function declarations are hoisted to the top. Similarly, variable declarations are also hoisted. Our original code is equivalent to:
var value; // declaration hoisted
value = 1;
function execute()
{
var value; // declaration hoisted
console.log(value); // value is declared but not yet assigned, so undefined
value = 2;
console.log(this.value);
this.value = 3;
}
You might wonder why the outer value (1) isn't used. This is due to JavaScript's scope chain and variable lookup rules. JavaScript first checks the current scope for the variable. If found, it uses that variable. If not, it moves up the scope chain until it finds the variable or reaches the global scope.
b. The second print statement outputs 1. Let's transform the code to make this clearer:
window.value = 1; // global variable
// Global function execute()
window.execute = function () {
console.log(value);
var value = 2;
console.log(this.value); // 'this' refers to window
this.value = 3;
}
// Calling the global function
window.execute();
When calling execute() without the 'new' keyword, we're essentially calling window.execute(). In this context, 'this' refers to the global object window. Therefore, this.value refers to window.value, which is 1.
2. var instance = new execute() outputs: *undefined* , *undefined*
a. The first undefined output is again due to variable hoisting, as explained above.
b. The second output is also undefined. JavaScript uses prototype-based inheritance rather than classes. When a function is called with the 'new' keyword, it acts as a constructor function. In this context, 'this' refers to the newly created object (instance in our case).
var value = 1;
function execute()
{
var value; // declaration hoisted
console.log(value); // undefined
value = 2;
console.log(this.value); // 'this' refers to the new object instance
this.value = 3;
}
var instance = new execute();
The key concept here is understanding how 'this' behaves in different contexts. When using 'new', 'this' refers to the newly created object, not the global object.
This interview question effectively tests understanding of JavaScript's core concepts: variable hoisting, scope chain, and the 'this' keyword.