Newsletter

JavaScript variable scope: local and global variables

In JavaScript, a variable has a range of visibility called its scope. Where you declare the variable decides that scope: inside a function it stays local to that function, outside any function it becomes global and readable from the whole script.

JavaScript variable scope: local and global variables

In JavaScript, variables have a range of visibility known as their scope. It is an important notion to grasp in JavaScript, because it is a frequent source of bugs: depending on where you declare a variable, its scope changes. Declare it inside a function and it can only be used inside that function. There are two kinds of variable, local variables and global variables.

javascript
var tutu = "tutu"; // 1

function maFonction() {
    var toto = "toto"; // 2
    return toto;
}
  1. tutu is what we call a global variable: it can be used anywhere in the script, functions included.
  2. toto is also a variable, but a local one: it cannot be used outside its own function.

Local variables

When you create a local variable, meaning a variable declared inside a function with var, it can only be used inside that function. The variable is said to be local, or to have the scope of the function where it was declared. It cannot be read from outside that function. The browser creates local variables when the function runs and removes them as soon as the function is done. Two more things worth knowing:

  • Two different functions can use variables with the same name without any naming conflict.
  • If the function is called several times, the variable can hold a different value each time.

Global variables

Global variables can be used anywhere in the script, they are declared outside any function. Their scope is said to be global.
Global variables are held in the memory of your browser. They therefore take up more memory than local ones, and they raise the risk of name clashes with other scripts. That is why you should stick to local variables wherever you can.

JavaScript

Damien Flandrin Web developer since 2010, creator of Gekkode and Email Impact. Every article is tested on a real project before publication. Contact
Newsletter

New tests, tutorials and projects, by e-mail.

Reproducible tests, versioned code, dated results. Never any spam.