Switchable Models, Personalization, and Onboarding Agent
Home / Blog /
Global Variable in JavaScript

Global Variable in JavaScript

Tabnine Team /
< 1 minute /
October 4, 2020

A Global variable is a variable that is declared in the global scope, making it a property of the global object.

Global variables are accessible from all other (local) scopes.

The global scope is a scope that contains every variable declared outside of a function (functions create their own scope, known as a local scope, and the variables declared inside functions are known as local variables).

Block statements do not create their own scope when included outside of a function, thus variables declared inside blocks are global (using the const or let keywords changes this).

The following examples explore working with global variables and scopes.

Example 1 – Defining a global variable:

The following declaration takes place outside of a function’s scope, meaning the toys array is a global variable:

const toys = ['Car', 'Airplane', 'Train'];

Example 2 – Defining a local variable:

This example defines the variable toys within the scope of a function, making it a local variable:

function getToys() { 
  const toys = ['Doll', 'Wand', 'Wings']; 
  return toys 


Related Articles:

JavaScript – How to use functions

JavaScript – Objects explained

JavaScript – How to Use Cookies