Code has been added to clipboard!

JavaScript Global Variables and Local Variables: Scopes Explained

Reading time 4 min
Published Aug 8, 2017
Updated Oct 1, 2019

JavaScript is one of the main web programming languages, so it should always be functional when a website opens. To make sure it is, the developer must know when to use JavaScript global variables, and when it is better to stay with the local scope.

This tutorial will teach you everything about scope in JavaScript - you'll be familiar with JavaScript global variables, as well as local ones. If you are looking for JavaScript static variables though, remember this language doesn't support static keywords (unlike other languages, like C or C++).

JavaScript Scope: Main Tips

  • Functions and objects are variables in JavaScript.
  • A JavaScript variable scope defines the visibility (accessibility) of the variable. Variables can be local and global.
  • JavaScript global variables are accessible throughout the whole web document.
  • Local variables are available only in the current function.

Local vs. Global

We're sure your intention is to understand when a global or a local variable is a better choice, and learn how to use them. Still, practice can't start without covering the bases in theory. To make proper choices between the two, you first have to understand their differences.

We will now review each of the scopes carefully and provide examples to ensure you understand the material. Soon, JavaScript variable scopes will seem to you like a no-brainer!

Local Scope

Local function variables are the ones which are declared inside of a function in JavaScript. Local variables can be accessed only from within the said function. Therefore, you can't reach them from any other function in your document.

It's good to use local variables in JavaScript functions because it allows you to use variables with the same name, as long as they are local variables that stay within separate functions. While using local variables, you can only access them in the current function, which means the program will only access a variable that is in its scope.

Example
// in here the "phone" variable can not be accessed

function simpleFunction(){

  var phone = "smartPhone";

  // here the "phone" variable can be accessed

}

Global Scope

All variables that are created outside of functions are called JavaScript global variables. Such objects can be accessed throughout the whole website. You must have different names for your global variables: otherwise, the browser will fail to present the action you want.

A global variable has a global JavaScript scope. All functions can access it throughout the web page:

Example
var phone = "SmartPhone";  
// code here can use "phone" 

function simpleFunction() {   

// code here can use "phone" 

}

Set Global Variables Automatically

A variable can automatically become global if you set a value to a variable that has not yet been declared. This can happen even if you assign a value to a variable in JavaScript functions:

Example
// code here can use "phone"

function myFunction() {   
   
  phone = "SmartPhone";   
 
  // code here can use "phone"

}

Note: you need to add var at the start of the statement to properly create a new local variable.

Note: to not create such global variable JavaScript should stay in strict mode while you work.

Global Variables in HTML

JavaScript global variables work in the whole JavaScript environment. From the first line of code, your global JavaScript variable scope begins and extends to the end of the script. Variables in JavaScript become available from the moment they are declared. They stop when the function ends.

However, JavaScript global variables belong to the window object in HTML and become available from the moment a person opens a browser window. Variables are deleted when the page is closed:

Example
// code here can use window.phone

function simpleFunction() {  
    
  phone = "SmartPhone";

}

JavaScript Scope: Summary

  • Local variables are available only within a function they have been declared in.
  • Global variables are accessible throughout the whole web document.
  • Variables that have not been declared, but have been assigned values (even within functions), become global automatically.
  • If you wish to not automatically generate global variable JavaScript should stay in strict mode.
  • In JavaScript static variables are not supported.
What Is JavaScript Used For?
Tutorial
Introduction
Output
Syntax
Comment
Commands
Operators
Comparison and Logical Operators
Data Types
Math.random()
Type Conversion
Function Definitions
Events
Objects
Object Properties
Prototype
Array
Sorting Arrays
Strings
Numbers
Number Format
Math Object
Onclick Event
Date
Date Formats
Scope
Regular Expressions
Reserved Words
Common Mistakes
Performance
Forms
Form Validation
Window: The Browser Object Model
Popup Boxes
Cookies
JSON
AJAX Introduction
AJAX Form
Automatic File Download
Functions
Array Methods
String Methods
Date Methods
Timing Events
Cheat Sheet
JavaScript in HTML
HTML DOM Methods
HTML DOM Changing HTML
HTML DOM Animation
HTML DOM EventListener
HTML DOM Navigation
HTML DOM NodeList
HTML DOM Element Nodes
Array Functions
Boolean
Calling a Function
Date Functions
Global Objects
Input Text
Operator
Statements
String Functions
Math
Math.random
Number
RegEx
alert
array.filter
array.length
array.map
array.reduce
array.push
array.sort
break and continue
className
confirm
decodeURIComponent
for
forEach
if
indexOf
innerHTML
location.reload
number.toString
onclick
onload
parseInt
prompt
replace
setAttribute
setInterval
setTimeout
slice
splice
string.includes
string.indexOf
string.split
style.display
submit
substr
substring
switch
test
throw, try and catch
toLowerCase
toUpperCase
use strict
while
window.history
window.location
window.navigator
window.screen