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 declare and use local and global variables in your JavaScript programs.

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

Here is the HTML code:

<html>
    <head>
        <title>Variable scope</title>
        <script src="script.js"></script>
    </head>

    <body>
        
    </body>
</html>

And here is the JavaScript code:

var user = "Joe"; // this is a global variable

function displayUser(){
    console.log(user + " inside function");
}

displayUser();

console.log(user + " outside function");

function displayOtherUser(){
    var user2 = "Sally"; // this is a local variable
    console.log(user2 + " inside function");
}

displayOtherUser();

// the line below will cause an error because we are trying to
// access the user2 variable outside its scope
console.log(user2 + " outside function");

Next tutorial: Arrays

Leave a Reply