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 Use The Array map() Method in JavaScript

How to Use The Array map() Method in JavaScript

Array map() is a method included in the Array.prototype property which was introduced in ECMAScript 5 (ES5) and is supported in all modern browsers. Map is

How to Use the typeof operator in JavaScript

How to Use the typeof operator in JavaScript

The typeof operator accepts an operand and returns the type of the provided operand as a string. The following sample code shows the typeof operator in

How to Use the substr Method in JavaScript

How to Use the substr Method in JavaScript

The substr() method extracts a part of a string from the larger whole. Note: Be careful to not confuse substr() with the substring() method! The example