I could not fully understand the difference between these two scopes, as some sources are old and some tell different things from each other. Could you please explain to me the difference between local scope and function scope in a simple way?
2 Answers
There is no difference between "local scope" and "function scope".
Up to and including ES5 there were only two scopes: global and "not global". The latter one would be called "local" or "function". Both terms means the same thing:
var a = "this is global scope";
function foo() {
var b = "this is local/function scope";
if (true) {
var c = "this is in the same local/function scope as b";
}
for (var i = 0; i < 4; i++) {
var d = "this is also in the same local/
function scope as b and c";
}
}
It is function because it is inside the function.
As of ES6 the term "local" scope might be a bit of a misnomer, since there are more scopes than just two. For example block scope for variables like let
or const
:
const a = "this is global scope";;
function foo() {
const b = "this is function scope";
if (true) {
const c = "this is in block scope";
}
for (let i = 0; i < 4; i++) {
const d = "this is also in block scope but different to c";
}
}
as well as module scope for any file that is a module:
export const a = "this is in module scope";

- 26,331
- 9
- 49
- 67
Local scope just refers to the scope available to a given variable, but function scope would refer to variables inside a function.
Here var x is inside a function, so it's only accessible inside the function.
function hi() {
var x = 'hello';
console.log(x);
}
hi();
console.log(x); // this will throw an error: "x is not defined"
Here var x is locally scoped to the window object, which is also called globally scoped, and thus it is available inside or outside the function:
var x = 'hello';
console.log(x);
function hi() {
x = 'world';
console.log(x);
}
hi();
console.log(x);