Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


Share this Page URL
Help

CHAPTER 4: JavaScript Primer > Using Variables and Types - Pg. 102

CHAPTER 4 JAVASCRIPT PRIMER Using Variables and Types You define variables using the var keyword and can optionally assign a value to the variable in a single statement. Variables that are defined in a function are local variables and are available for use only within that function. Variables that are defined directly in the script element are global variables and can be accessed anywhere, including other scripts. Listing 4-6 demonstrates the use of local and global variables. Listing 4-6. Using Local and Global Variables <!DOCTYPE HTML> <html> <head> <title>Example</title> </head> <body> <script type="text/javascript"> var myGlobalVar = "apples"; function myFunc(name) { var myLocalVar = "sunny"; return ("Hello " + name + ". Today is " + myLocalVar + "."); }; document.writeln(myFunc("Adam")); </script>