In this tutorial, you will learn about the JavaScript variable scope that determines the visibility and accessibility of variables.

What is variable scope

Scope determines the visibility and accessibility of a variable. JavaScript has three scopes: global scope, local scope, and block scope.

Global scope

When you execute a script, the JavaScript engine creates a global execution context.

It also assigns variables that you declare outside of functions to the global execution context. These variables are in the global scope. They are also known as global variables.

See the following example:

var message = 'Hi';

The variable message is global scoped. It can be accessible everywhere in the script.

JavaScript Global Variables

Local scope

Variables that you declare inside a function are local to the function. They are called local variables. For example:

var message = 'Hi';

function say() {
    var message = 'Hello';
    console.log('message');
}

say();
console.log(message);

Output:

Hello
Hi

When the JavaScript engine executes the say() function, it creates a function execution context. The variable message that declares inside the say() function is bound to the function execution context of say() function, not the global execution context.

JavaScript Local Variables

Scope chain

Consider the following example:

var message = 'Hi';

function say() {
    console.log(message);
}

say();

Output:

Hi

#javascript #programming #developer #web-development

JavaScript Runtime Tutorial - JavaScript Variable Scopes
1.80 GEEK