Javascript Function Variable Scope Question 3

Description

Javascript Function Variable Scope Question 3


let x = 1;      // global variable

function start()//from   w  w w. j a  v  a 2 s  .  co  m
{
   let x = 5;   // variable local to function start

   console.log( "local x in start is " + x );

   functionA(); // functionA has local x
   functionB(); // functionB uses global variable x
   functionA(); // functionA reinitializes local x
   functionB(); // global variable x retains its value

   console.log( 
      "<p>local x in start is " + x + "</p>" );
} // end function start

function functionA()
{
   let x = 25;  // initialized each time 
                // functionA is called

   console.log( "local x in functionA is " + 
                     x + " after entering functionA" );
   ++x;
   console.log( "local x in functionA is " +
      x + " before exiting functionA");
} // end functionA

function functionB()
{
   console.log( "global variable x is " + x + " on entering functionB" );
   x *= 10;
   console.log( "\nglobal variable x is " + x + " on exiting functionB");
} // end functionB
start();
local x in start is 5/*from  w  w w  . j av a 2  s  .com*/
local x in functionA is 25 after entering functionA
local x in functionA is 26 before exiting functionA
global variable x is 1 on entering functionB

global variable x is 10 on exiting functionB
local x in functionA is 25 after entering functionA
local x in functionA is 26 before exiting functionA
global variable x is 10 on entering functionB

global variable x is 100 on exiting functionB
local x in start is 5



PreviousNext

Related