HTML Dog
Skip to navigation

Scope

Scope is the term used to mean variable visibility — a variable’s scope is the part of your code that can access and modify that variable. JavaScript has function scope — but what does that mean and how is it different to other languages?

Scope is, in many programming languages, dictated by the block in which the variable was declared. A block, in C-like languages, is anything between two curly braces, or indentation in a language like Python. For example, the b variable below is not available outside the curly braces in which it was declared:


var a = 10;

if (a > 5) {
    var b = 5;
}

var c = a + b; // Wouldn't work!

Function scope

JavaScript does things a little differently. It uses function scope. This means that variables are not visible outside of the function in which they were declared. If they are not declared inside a function then they are available globally.

The example below demonstrates that a variable is only visible inside the function in which it was declared. The doSomething function is the variable a’s scope.


var doSomething = function () {
    var a = 10;
};

doSomething();

console.log(a); // a is undefined

Comparing this to the block scope example above, you can see that, in JavaScript, b is available:


var a = 10;

if (a > 5) {
    var b = 5;
}

var c = a + b; // c is 15

Child scopes

Variables are available in child scopes of their own scope. For example, doSomethingElse is a child of doSomething, so a is visible inside doSomethingElse.


var doSomething = function () {
    var a = 10;
var doSomethingElse = function () {
    console.log(a); // a is 10
};
doSomethingElse();
};

doSomething();

Functional scope is a very powerful tool for creating elegant code, as we’ll see, but it can take some time to get your head around.