Variable Scope Variable variable whos got the variable
Variable Scope Variable, variable, who’s got the variable? © Copyright 2016, Fred Mc. Clurg All Rights Reserved
Variable Scope Defined: Variable scope has to do with where variables are “visible” in a program. Local Scope: Scope that is local to function and does not have a value outside the function. Global Scope: Scope that is visible inside and outside the function 2
Global Variable Scope Variables defined outside of the function have global scope. function clobber() { star = "John Wayne"; // note: no var keyword // displays "John Wayne" console. log( "Inside clobber(): " + star ); } var star = "Danny Kaye"; // global variable // displays "Danny Kaye" console. log( "Before clobber(): " + star ); clobber(); // function call // displays "John Wayne" console. log( "After clobber(): " + star ); global. Scope. html 3
Parameter Variable Scope Variables passed to the function as arguments have local scope. function clobber( star ) { // local variable parameter // displays "Danny Kaye" console. log( "Inside clobber() before: " + star ); star = "John Wayne"; // displays "John Wayne" console. log( "In clobber() after: " + star ); } var star = "Danny Kaye"; // global variable // displays "Danny Kaye" console. log( "Before clobber() call: " + star ); clobber( star ); // variable argument "Passed by Value" // displays "Danny Kaye" console. log( "After clobber() call: " + star ); param. Scope. html 4
Local Variable Scope Variables defined inside of the function have local scope. function clobber() { var star = "John Wayne"; // local variable // displays "John Wayne" console. log( "Inside clobber(): " + star ); } var star = "Danny Kaye"; // global variable // displays "Danny Kaye" console. log( "Before clobber(): " + star ); clobber(); // function call // displays "Danny Kaye" console. log( "After clobber(): " + star ); local. Scope. html 5
- Slides: 5