DEV Community

Cover image for JS Fundamentals: Scope explained
Allison Cortez
Allison Cortez

Posted on

JS Fundamentals: Scope explained

What is Scope?

Scope is the concept of where something is available. The actual MDN definition states it's the context in which values and expressions are "visible" or can be referenced.

In Javascript, there are 3 types of scope: Global, Function, and Block Scope.

Global Scope

When a variable or function has a global scope, that means it can be accessed everywhere in our code.

var a = "I'm a global variable!";

function myFunct(){
  console.log(a); // has access to 'a' since it has global scope.
}

myFunct() // 'I'm a global variable!'.
Enter fullscreen mode Exit fullscreen mode

Tip: If a variable or function is NOT declared inside a function or block, it most likely falls under the global scope.

Function Scope

When variables, functions, or parameters are declared inside of a certain function, they are only accessible within that specific function.

function eatDinner(){
  var item = 'Turkey';
  console.log(`I love ${item}!`)
}

eatDinner(); // 'I love Turkey!'
console.log(item); // 'ReferenceError: item is not defined.'
Enter fullscreen mode Exit fullscreen mode

From outside of the function, we can't reference anything declared inside of it.

Block Scope

A block statement creates its own scope.

Variables declared with var are not block-scoped.

if (true){
  var myVar = 42;
}

myVar; // => 42
Enter fullscreen mode Exit fullscreen mode

Variables declared with const and let are block-scoped.

if (true){
  const myVar = 42;

  let secondVar = 1000;
}

myVar;
// Uncaught ReferenceError: myVar is not defined

secondVar;
// Uncaught ReferenceError: secondVar is not defined
Enter fullscreen mode Exit fullscreen mode

Things to keep in mind when defining scope

Variables created without const, let, or var keywords will be globally-scoped, regardless of where they are in your code.

const greeting = 'Hey guys'; // global scope
holiday = 'Thanksgiving'; // global scope

if (true){
  lastName = 'Cortez'; // global scope
  let firstName = 'Allison'; // block scope
}

lastName;
// => "Cortez"
firstName;
// 'ReferenceError'

Enter fullscreen mode Exit fullscreen mode

Generally, you should never use global variables.

For example, say you're storing sensitive information...

function userAccount(){
  password = 'secretPassword';

}

password;
// => "secretPassword"
Enter fullscreen mode Exit fullscreen mode

In our example, we probably wanted our password variable to have a function scope.. BUT since it had global scope, we got access to sensitive information when we shouldn't have.

It's best practice to make variables and functions available only where they're needed.

MDN Scope

Top comments (0)