Sitemap
Frontend Essentials

Learn more on JavaScript, functional programming, and front-end development.

An introduction to scope in JavaScript

Global, module, function and block scopes, scope chain and more

5 min readApr 1, 2019

--

Press enter or click to view image in full size
Photo by the author

Scope defines the lifetime and visibility of a variable. Variables are not visible outside the scope in which they are declared.

JavaScript has module scope, function scope, block scope, lexical scope and global scope.

Global Scope

Variables defined outside any function, block, or module scope have global scope. Variables in global scope can be accessed from everywhere in the application.

When a module system is enabled it’s harder to make global variables, but one can still do it. By defining a variable in HTML, outside any function, a global variable can be created:

<script>
let GLOBAL_DATA = { value : 1};
</script>
console.log(GLOBAL_DATA);

When there is no module system in place, it is a lot easier to create global variables. A variable declared outside any function, in any file, is a global variable.

Global variables are available for the lifetime of the application.

Another way for creating a global variable is to use the window global object anywhere in the application:

window.GLOBAL_DATA = { value: 1 };

--

--

Frontend Essentials
Frontend Essentials

Published in Frontend Essentials

Learn more on JavaScript, functional programming, and front-end development.

Cristian Salcescu
Cristian Salcescu

Written by Cristian Salcescu

Author of Functional Programming in JavaScript. Enthusiastic about sharing ideas. https://www.amazon.com/gp/product/B08X3TPCQ8

No responses yet