A locally scoped variable is a variable declared with the keyword var within a function. Local refers to the context of the function itself. When you declare a variable within a function it is made available throughout the entire function, and it is completely unavailable outside of the function.
For example:
var x = 1;
function hello() {
alert(x);
var y = 2;
}
hello();
alert(y);
If you run this code you will find that the function
hello has access to
x because it is a global variable, but when we try to alert
y outside of the function we get an Uncaught ReferenceError. That's because
y is only available within the scope it was created.
It is also important to note that parameters passed into a function are scoped locally. So in the following example:
function sendMessage(message) {
alert(message);
}
sendMessage('hello, friend');
console.log(message);
we see the alert but get another Uncaught ReferenceError because the
message variable is declared as a parameter of the function
sendMessage and is only available from within the function itself.
As JavaScript allows for nesting functions, a variable declared within a function is also available within its nested functions. Take this for example:
function go() {
var x = 2;
function add3() {
return x + 3;
}
return add3();
}
alert(go());
You would never write this, but if you did you would find that
x is available from within the
add3 function. But as you might now assume, a local variable declared within a nested function is not available to its parent function.
Keep in mind that in JavaScript, unlike many other programming languages, there is no block level scope. Instead JavaScript uses function level scoping.