Go back to JavaScript Index

What is scope?

Scope refers to the current context of code, which determines the accessibility of variables.

Variables can exist either outside of blocks (global scope) or inside blocks (block scope).

Global scope

When we talk about global scope, the variables are declared outside of code blocks and may be accessed everywhere - also inside code blocks.

Let's have a look at an example:

let color = "green";
const returnColor = () => {
return color;
1.0 | Global scope

If you run the program, you will see that the function returns the value of the variable eventhough it was declared outside of the function and used inside.

Block scope

When a variable is declared inside of a function on the other hand, it is only accessible inside the function. This type of variables is known as a local variable.

Let's have a look at an example:

const logColor = () => {
let color = "green";
1.1 | Block scope

Scope polution

So why not just make all variables globale?

Because globale variables, that e.g. run through different functions are harder to keep track of and makes it hard getting an overview.

Next up

What's next?

Next up: The DOM