DEV Community

Amera White
Amera White

Posted on

IDK: Local Scope vs Global Scope

In order to discuss the differences between Local scope and Global scope, we first need to know what scope even means. So, What is scope? Basically, scope describes where a variable was declared and where it can be accessed.

Great! now that you have an idea of what the scope of a variable is referencing. Let’s move on to figure out the difference between Local vs Global scopes.

What are Local scope variables?

Local variables refer to those declared inside of a function block. This means the variable can only be used and accessed within that particular block of code.

Example:


function localScopeBlock() {  
let x = 5;  
return x
}

console.log(localScopeBlock()) //this will return the number 5 in the console

//Next, try to log the x variable, along with the function call 

console.log(localScopeBlock(), x) //this will cause an error in the console 

Enter fullscreen mode Exit fullscreen mode

The error occurred because x was declared inside of the code block and can not be accessed.

What are Global scope variables?

Global variables refer to those that are declared outside of a function block. This means the variable can be accessed and used from anywhere in the javaScript document, because it is at the highest level in the scope tree.

Example:

let x = 3;

function globalScopeBlock() {  
let x = 5;
return x;
}

console.log(globalScopeBlock(), x) //this will show the numbers 5 and 3 in the console

Enter fullscreen mode Exit fullscreen mode

Unlike the previous example, the console doesn’t throw an error.
The function call returned 5 (local scope variable), then the number 3 was logged to the console from our global variable located outside of the function.

Side-note

When declaring variables, you should use let and const to be more precise in your javascript code. When you use var to declare variables they are automatically move to the global scope. This is not best practice and can ultimately create unintended errors in your code.

Top comments (0)