If JavaScript is dynamic scoping, what would be the last console.log() result in the following code?

55 Views Asked by At

This is how I defined the functions and the variable x,y,z is defined with some integer.

var a = 0;
var x = 1;
var y = 2;
var z = 3;

function f(n) {
    a = n;
}
function g(){
    console.log(a);
}
function h(){
    f(x); g();
}
function k() {
    var a = 0; g(); f(y);
}
f(z); g(); k(); g(); h(); g();

The following is my thoughts on if the code above is dynamically scope:

f(z){
  a = z; // The value of a became z
}
g(){
  console.log(a); // Printing out the value of z
}
k(){
  var a = 0;
  g(){
    console.log(a); // Printing out 0
  }
  f(y){
    a = y; // Assign the value of y to the variable a initialized 5 lines above
  }
}
g(){
  console.log(a); // Printing out the value of z
}
h(){
  f(x){
    a = x;
  }
  g(){
    console.log(a) // Printing out the value of x
  }
}
g(){
  console.log(a) // Printing out value of z or x ??
}

Not sure what the last console.log will output.

1

There are 1 best solutions below

6
AudioBubble On BEST ANSWER

See the example snippet with it's comments:

var a = 0;
var z = 1;
var x = 2;
var y = 4;
function f(n) {
    a = n;
}
function g(){
    console.log(`value of var a is ${a}`); // output var a value to console
}
function h(){
    f(x);  // a becomes 2 here since x = 2
    g();  // output var a value to console
}
function k() {
    var a = 0; // this sets a to 0 only in function scope
    console.log(`function scope value of var a is ${a}`);
    g(); // output var a value to console which is 1 here not 0
    f(y); // a becomes 4 here since y = 4
}
f(z); 
g(); 
k(); 
g(); 
h(); 
g();
console.log(`final value of var a is ${a}`);

The below example works as you want (if i understood your question). Simply omit var before a in function k().

var a = 0;
var z = 1;
var x = 2;
var y = 4;
function f(n) {
    a = n;
}
function g(){
    console.log(`value of var a is ${a}`); // output var a value to console
}
function h(){
    f(x);  // a becomes 2 here since x = 2
    g();  // output var a value to console
}
function k() {
    a = 0; // this sets a to 0 only in function scope
    console.log(`function scope value of var a is ${a}`);
    g(); // output var a value to console which is 1 here not 0
    f(y); // a becomes 4 here since y = 4
}
f(z); 
g(); 
k(); 
g(); 
h(); 
g();
console.log(`final value of var a is ${a}`);