Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote