Global Variable in JavaScript

  • 1 min read
  • October 4, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

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

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement

How to use the for…of Statement in JavaScript

How to use the for…of Statement in JavaScript

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript. JavaScript offers many different types of loops, each