Consdier the following program (as we discussed in the class). What value of x i
ID: 3605615 • Letter: C
Question
Consdier the following program (as we discussed in the class). What value of x is displayed in function sub1? Select one best answer.
/* program begins here */ var x;
function sub1( ) {
document.write("x = " + x + "<br />");
}
function sub2( ) { var x;
x = 10;
sub1( );
}
x = 5;
sub2( );
/* program ends here */
5 with static scoping, 10 with dynamic scoping
10 with static scoping, 5 with dynamic scoping
5 with static or dynamic scoping
10 with static or dynamic scoping
undefined for static scoping
undefined with dynamic scoping
Explanation / Answer
Static scoping :
function sub1( ) {
document.write("x = " + x + "<br />");
}
function sub2( ) { var x;
x = 10;
sub1( );
}
x = 5;
sub2( );
Here the value 5 is not changed due to the function call and its operations.
document.write("x = " + x + "<br />"); // It prints x value as 5.
Dynamic scoping:
x = 5; // initially the value is 5
sub2( ); // control transfer to called function
function sub2( ) {
var x;
x = 10; // Here we use dynamic scoping so the value of x is changed from 5 to 10
sub1( ); // control transfered to sub1
}
function sub1( ) {
document.write("x = " + x + "<br />"); // It prints x value as 10
So 5 with static scoping, 10 with dynamic scoping
Option 1 correct.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.