Variable scope

Now that you are using functions in JavaScript, it is really important to understand variable scope. JavaScript has two variable scopes: global and local.

  • A global variable is a variable which is declared outside a function and its value can be accessed and modified throughout your program
  • A local variable is a variable which is declared inside a function definition. It is created and then destroyed every time the function runs, and cannot be accessed or modified from outside the function.

Make sure that you watch the video on variable scope here to see how it works. Sample code is available for you to try out below.

<!DOCTYPE html>
<html lang="en"
 <meta charset="utf-8"/>
 <title>JavaScript - Variable scope</title>
 <script type="text/javascript">
 // A local variable is defined inside a function and can only be used inside a function it's declared in
 // A global variable can be used anywhere in the program
 var name = "Smith"; //global variable
 function printName(){
 document.write(name + " inside function<br/>");
 // the name variable is being used inside the function
 printName(); // this will run the printName function
 document.write(name + " outside of function<br/>"); // this uses the name variable outside of the function
 function printName2(){
 var name2="Mary"; // name2 is a local variable created inside this function
 document.write(name2 + " inside function<br/>");
 printName2(); // this will run the printName2 function
 // what will happen when the line of code below runs?
 document.write(name2 + " outside of function<br/>");
 // the statement on the line above will not work because the variable name2 cannot be accessed outside of the function
 // If you go to the JavaScript Console in your browser, you will see an error has been reported when running the code
 // The error will look like: Uncaught ReferenceError: name2 is not defined
 // This error occurs because name2 can only be used by the printName2 function, and not outside the function.