DEV Community

Ben D.
Ben D.

Posted on

Javascript Scope

A scope in Javascript means the area of code in which certain variables are able to be accessed.

Variables are declared using let,const, and var.

var creates global scoped variables, but this is problematic if this variable is declared in multiple places as overwrites can happen.

The best reference on the internet in my opinion is Dimitri Pavlutin's blog on Scope.

This JS Scope Visualized blog is also amazing blog for visual learners. It's a 7 part series about JS, and has a section on scope which helped me tremendously

There are three types of scope: global, function and block.

Global scope is pretty straightforward, it means that the variables can be accessed from anywhere in the code.

Image description

Local Scope

if, for, and while statements create a scope.

function fly() {
  // "fly" function scope
  const message = 'We're going to land in the river';
  if (true) {
    // "if" code block scope
    const pilot = 'Sully';
    console.log(message); // 'That seems dangerous'
  }
  console.log(pilot); // pilot is not defined
}
console.log(message); // message is not defined
Enter fullscreen mode Exit fullscreen mode

Standalone code blocks also create a scope:

{ 
let scope = 'this is block scoped'
} 

console.log(scope) = this would return an error
Enter fullscreen mode Exit fullscreen mode

Also local scope


function localScope() {
    const array = [1, 2, 3, 4, 5];
    let sum = 0;

}

console.log(array); //arr is not defined
console.log(sum); //array is not defined
Enter fullscreen mode Exit fullscreen mode

There are nested scopes too, an inner function within an outer function has access to the outer scope.

Image from Gyazo

In summary,

The Scope is the area in code from where a variable can be accessed.

It can be broken down to:

Global Scope
Local Scope: Function Scope & Block Scope

For the best explanations, please reference the links further up. If you are interested in copy/pasting your code into a web app for a visual representation of scope, then this is a cool site:

JS Visualizer

Top comments (1)

Collapse
 
boriskarlof7 profile image
BKarlof

Thanks, very instructional!