Home > OS >  Variable/parameter/function visibility OF a function within a function - SCOPE Question
Variable/parameter/function visibility OF a function within a function - SCOPE Question

Time:11-20

I have been working on this for 3 hours exploring videos on scope, functions, function strings, and variable parameters. But I cannot get it right!

Quiz on Scope

Test your understanding of variable visibility.

var outside = 'outside';

function a() {
  var aVar = 'a';

  function aInner1() {
    var aInner1Var = 'aInner1Var';

    function aInner1Inner() {
      var aInner1InnerVar = 'aInner1InnerVar'; 
    }
  }

  function aInner2(aInner2Param) {
    var aInner2Var = aInner2Param;
  }
}

function b(bParam) {
  console.log(bParam);
}

Which of the following statements are true for the above code? Select 1 or more.

  1. a is visible to b
  2. b and bParam are visible to a
  3. aInner1InnerVar is only visible to aInner1Inner and aInner1
  4. aInner1InnerVar is visible to aInner1Inner
  5. aVar is visible to aInner2
  6. aInner1Var is visible to aInner2
  7. aInner2Param is visible to aInner1

My thoughts so far:

I know a local function can see the parent function, (basically anything above it). But I don't know if it can see only the function name. Or also the parameter/variable/etc. And I know all functions can see global variables.

my attempt to pseudocode

function one() {            // one can see oneA, oneB, oneAB, two
   function oneA() {        // oneA can see one, oneB  
       function oneB() {    // oneB can see one, oneA, oneB 
     }
   }
   function oneAB() {       // oneAB can see one, two
     }
}
function two() {            // two can see one
}
  1. a is visible to b // global scope function

    • YES
  2. b and bParam are visible to a // function name "a/b" yes, not sure for param

    • ?
  3. aInner1InnerVar is only visible to aInner1Inner and aInner1 // var in block visible to function and outer function

    • ?
  4. aInner1InnerVar is visible to aInner1Inner // var in block visible to function

    • ?
  5. aVar is visible to aInner2 // function can see var inside another function

    • NO
  6. aInner1Var is visible to aInner2 // function can see var of funct within a funct

    • NO
  7. aInner2Param is visible to aInner1

    • NO

CodePudding user response:

  • 1 = yes - function a and b are in the same scope

  • 4 = yes - the variable is in the body of the function / in scope

  • 5 = yes - the variable is within the parent function

  • 2, 3, 6, 7 = no

  • Related