cover-img

All About JavaScript Scope

19 January, 2023

14

14

0

In JavaScript, a scope refers to the current context of code execution. Scopes can be either global or local. A global scope is the default scope and is created when a JavaScript file is loaded into a web page. In a global scope, all variables and functions are defined on the window object.

A local scope, on the other hand, is created inside a function. When a function is executed, a new local scope is created, and any variables or functions defined inside that function are only accessible within the function's local scope. This is known as variable shadowing, as local variables with the same name as a global variable will take precedence over the global variable within the function's local scope.

JavaScript also has the concept of block-level scopes, which are created inside curly braces. The most common example of block-level scopes in JavaScript is the if statement. Variables defined inside a block-level scope are only accessible within that block.

Here's an example to illustrate the different scopes in JavaScript:

const globalVariable = 'This is a global variable';

function myFunction() {
const localVariable = 'This is a local variable';
console.log(globalVariable); // Output: 'This is a global variable'
console.log(localVariable); // Output: 'This is a local variable'
}

console.log(globalVariable); // Output: 'This is a global variable'
console.log(localVariable); // Output: ReferenceError: localVariable is not defined

In this example, the globalVariable is defined in the global scope and is accessible from anywhere in the code. The localVariable, on the other hand, is defined inside the myFunction function and is only accessible within that function's local scope. Trying to access the localVariable outside of the function will result in a ReferenceError.

Further Reading

You may want to read more about the let, const, and var keywords and their impact on the scope from this article:

https://www.freecodecamp.org/news/understanding-let-const-and-var-keywords/


14

14

0

ShowwcaseHQ
Showwcase is where developers hang out and find new opportunities together as a community

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2025. Showcase Creators Inc. All rights reserved.