Q. What would be the most appropriate output for the following code snippet?
Code:
var p=15 , q=10
var object = { p : 20 }
with(object)
{
alert(q)
}
β
Correct Answer: (D)
10
Explanation:
The with statement in JavaScript is used to extend the scope chain for a specific object, making its properties accessible without explicitly referring to the object.
Step-by-Step Execution:
var p = 15, q = 10; // Declaring two global variables
var object = { p: 20 }; // Creating an object with a property 'p'
with (object) {
alert(q); // Attempting to access 'q'
}
- The with(object) block adds object to the scope chain.
- When accessing q, JavaScript first looks inside object.
- Since q is not defined inside object, JavaScript falls back to the global scope, where q = 10.
- So, the output will be 10.
Why Not Other Options?
- (A) 20 β Incorrect, because q is not present in object, so p: 20 has no effect.
- (B) Error β Incorrect, as q exists globally and no error occurs.
- (C) 15 β Incorrect, because p = 15 is also ignored; the focus is only on q.
Thus, the correct answer is 10.