Variable scope in JavaScript

Variable scope refers to the context that a variable is defined in. 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.

This video explains variable scope when using functions and how to setup and use local and global variables in your JavaScript programs. You can watch the video below or click here to view it on YouTube. You can also find more information about variable scope in JavaScript here.

The sample code is below shows how to use local and global variables in JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
 <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.
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Arrays

Leave a Reply