JavaScript 009: Scope

Neha
GigaGuardian
Published in
2 min readDec 16, 2022
ImageSource

Scope

In JavaScript, scope refers to the visibility of variables and functions within a program. In other words, scope determines which variables and functions can be accessed and used by other parts of the code.

There are two main types of scope in JavaScript: local scope and global scope. A variable or function that is defined within a block of code, such as a “for” loop or an “if” statement, is only visible and accessible within that block of code. Such a variable is said to have local scope. On the other hand, a variable or function that is defined outside of any block of code is visible and accessible throughout the entire program. Such a variable is said to have global scope.

It’s important to understand scope in JavaScript because it can affect how our code runs.

For example, if we try to access a locally-scoped variable from outside of its block of code, we will get an error. This is why it’s generally considered good practice to use local variables as much as possible, to avoid potential conflicts with other parts of your code.

Here is an example of local and global scope in JavaScript:

// This variable has global scope because it is defined outside of any block of code
var globalVariable = "hello";

// This function has global scope because it is defined outside of any block of code
function globalFunction() {
// In this function, we can access the globalVariable because it has global scope
console.log(globalVariable);
}

// This function also has global scope
function localScope() {
// This variable has local scope because it is defined within this function
var localVariable = "world";

// In this function, we can access the localVariable because it has local scope
console.log(localVariable);

// However, if we try to access the localVariable from outside of this function, we will get an error
// because it only has local scope
}

// If we try to access the localVariable from outside of the localScope function, we will get an error
console.log(localVariable); // Uncaught ReferenceError: localVariable is not defined

In the example above, `globalVariable` and `globalFunction` are defined outside of any block of code, so they have global scope. This means they are visible and accessible throughout the entire program.

On the other hand, `localVariable` is defined within the `localScope` function, so it has local scope. This means it is only visible and accessible within the `localScope` function. If we try to access it from outside of that function, we will get an error.

I hope you enjoyed this introduction to scope!

Follow me: LinkedIn, Twitter

--

--