Scope - Falicer/Project_Tech_2021 GitHub Wiki

JS Scope

Javascript Scope

The scope manages visibility your variables within blocks, functions and modules. Each new block, function and/or module creates a new scope for the variables included in it.

Types of scopes

There are 2 types of scopes:

  • Local Scope
  • Global Scope

Local Scope

Variables declared within a function belong to the Local Scope, these variables can only be accessed within the function, for example:

if (true) {
  const message = 'Hello';
}

The const message is only declared within the function so if you would for example try to console.log(message) outside of this function you would get:

console.log(message); // ReferenceError: message is not defined

Because the message variable isn't declared outside of the function.

Global Scope

Variables declared outside of a function, block or module belong to the Global Scope, all scripts and functions on a web page can access this variable, so beware when making global variables.

Example of a global variable:

var carName = "Volvo";
// code here can use carName

function myFunction() {
  // code here can also use carName
}

The variable carName can now be accessed from everywhere because it was declared outside of a function.

Now let's try to combine them in a way, with this example:

// Initialize a global variable
var species = "human";

function transform() {
  // Initialize a local, function-scoped variable
  var species = "werewolf";
  console.log(species);
}

// Log the global and local variable
console.log(species);
transform();
console.log(species);

We now have var species declared outside and within a function and we log both of them, in these type of codes the output of console.log would look like:

human
werewolf
human

This is because the function transform() is called and that function changes the var species to werewolf within the function and console.log it.

Sources

JavaScript Scope. (z.d.). Www.W3schools.Com. Geraadpleegd op 25 mei 2021, van https://www.w3schools.com/js/js_scope.asp#:%7E:text=JavaScript%20has%20function%20scope%3A%20Each,visible)%20from%20outside%20the%20function.

Pavlutin, D. (2020, 24 april). A Simple Explanation of Scope in JavaScript. Dmitri Pavlutin Blog. https://dmitripavlutin.com/javascript-scope/

Rascia, T. (2021, 23 mei). Understanding Variables, Scope, and Hoisting in JavaScript. DigitalOcean. https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript