Prior to ES6 (the current version of JavaScript), JavaScript had only function level scope. That is, the following:

function foo() {
    console.log('before block: ' + bar);      // prints 'undefined'
    if(true) {
        var bar = 1;
        console.log('inside block: ' + bar);  // prints 1
    }
    console.log('outisde block: ' + bar);     // prints 1
}

Is exactly equivalent to:

function foo() {
    var bar;
    console.log('before block: ' + bar);      // prints 'undefined'
    if(true) {
        bar = 1;
        console.log('inside block: ' + bar);  // prints 1
    }
    console.log('outisde block: ' + bar);     // prints 1
}

(As a matter of fact, what I've just shown is called "hoisting", which is exactly what JavaScript does: all variable declarations are hoisted to the top of the function; assignments are left where they are.)

In contrast, languages like C# have block level scope. This would result in a compile error:

public void Foo() {
    if(true) {
        var foo = 1;
        Console.WriteLine("inside block: " + foo);
    }
    Console.WriteLine("outside block: " + foo);  // WILL NOT COMPILE
}

But you can have this:

public void Foo() {
    var foo = 1;
    if(true) {
        foo = 2;
        Console.WriteLine("inside block: " + foo);  // prints 2
    }
    Console.WriteLine("outside block: " + foo);     // prints 2
}
Answer from Ethan Brown on Stack Overflow
Top answer
1 of 3
22

Prior to ES6 (the current version of JavaScript), JavaScript had only function level scope. That is, the following:

function foo() {
    console.log('before block: ' + bar);      // prints 'undefined'
    if(true) {
        var bar = 1;
        console.log('inside block: ' + bar);  // prints 1
    }
    console.log('outisde block: ' + bar);     // prints 1
}

Is exactly equivalent to:

function foo() {
    var bar;
    console.log('before block: ' + bar);      // prints 'undefined'
    if(true) {
        bar = 1;
        console.log('inside block: ' + bar);  // prints 1
    }
    console.log('outisde block: ' + bar);     // prints 1
}

(As a matter of fact, what I've just shown is called "hoisting", which is exactly what JavaScript does: all variable declarations are hoisted to the top of the function; assignments are left where they are.)

In contrast, languages like C# have block level scope. This would result in a compile error:

public void Foo() {
    if(true) {
        var foo = 1;
        Console.WriteLine("inside block: " + foo);
    }
    Console.WriteLine("outside block: " + foo);  // WILL NOT COMPILE
}

But you can have this:

public void Foo() {
    var foo = 1;
    if(true) {
        foo = 2;
        Console.WriteLine("inside block: " + foo);  // prints 2
    }
    Console.WriteLine("outside block: " + foo);     // prints 2
}
2 of 3
5
function scopeTest() {

/* consider this simple for loop
    to be the "block" that we were
    talking about earlier
*/
for (var i = 0; i <= 5; i++)
{
  var inFor = i; 
}

alert(inFor);  // what happens here?

}


// call the function defined above
scopeTest( );

In the code above, we have a variable called inFor that was declared in a for loop. We then try to access the inFor variable outside the for loop in the alert statement.

If the code above does not alert anything then we know it's because Javascript uses block scope. In a block scoped language, the variable inFor will not be visible outside of the for loop. This means that if Javascript is a block scoped language, then the call to "alert(inFor);" will not recognize the inFor variable, and nothing will be output to an alert box.

But, the code above actually outputs a "5", which means that the inFor variable does exist outside of the for loop, which must mean that Javascript does NOT have block scope. And there is our answer - Javascript does not have block scope.

function scopeTest() {

var x = 2;

//this is always true:
if(x == 2)
{
  var y = 15;
  for (var i = 0; i <= 5; i++)
  {
    var inFor = i; 
  }
} 

  console.log(y); // y is defined, prints 15   
  console.log(i);  // i is defined, prints 6
  console.log(inFor);  // inFor is defined, prints 5

}

You can see in the code above that the variables y, i, and inFor are declared either inside the if statement or inside the for loop. But, even though those variables are declared inside those separate "blocks", they are still visible to the rest of the function. This is because all of those variables are declared inside one function - which is what function scope is all about.

Block scope vs Function scope

So, if Javascript doesn't use block scope, then what kind of scope does it use?

Well, Javascript uses something called function scope.

Basically, the difference between function scope and block scope is that in a language that uses function scope, any variables declared within a function are visible anywhere within that same function. But with block scope, the visibility of variables is confined to any given block (whether it's an if statement, where/for loop, etc) enclosed by curly braces.

http://www.programmerinterview.com/index.php/javascript/javascript-block-scope/ http://www.programmerinterview.com/index.php/javascript/javascript-function-scope/

    {
     here you can't access both a and b
     var a=1
     here you can access only a
        {
        here you can access only a
        var b=3
        here you can access both a and b
        {
        here you can access both a and b
        }
        here too you can access both a and b
        }
        here you can access only a
        }
       here you can't access both a and b
๐ŸŒ
GreatFrontEnd
greatfrontend.com โ€บ questions โ€บ quiz โ€บ explain-the-difference-between-global-scope-function-scope-and-block-scope
Explain the difference between global scope, function scope, and block scope | Quiz Interview Questions with Solutions
September 5, 2021 - Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within {}) they are declared in.
๐ŸŒ
Medium
medium.com โ€บ nerd-for-tech โ€บ function-scope-block-scope-in-js-d29c8e7cd216
Function Scope & Block Scope in JS
April 10, 2021 - Function Scope: When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function. Block Scope: A variable when declared inside the if or switch conditions or inside for or while ...
๐ŸŒ
Medium
medium.com โ€บ @shivanisingh16012004 โ€บ block-scope-vs-function-scope-implications-for-code-maintainability-c732384d720f
Block Scope Vs. Function Scope: Implications For Code Maintainability | by Shivani Singh | Medium
October 1, 2024 - In an article on variable scopes ... of a program. ... On the other hand, function scope means those variables that are only recognized within the function in which they are initialized....
๐ŸŒ
Coolhead
blog.coolhead.in โ€บ difference-between-function-scope-and-block-scope-in-javascript
Difference between function scope and block scope in ...
June 18, 2024 - Function Scope: When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function. Block Scope: A variable when declared inside the if or switch conditions or inside for or while ...
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Glossary โ€บ Scope
Scope - Glossary | MDN
const x = "declared outside function"; exampleFunction(); function exampleFunction() { console.log("Inside function"); console.log(x); } console.log("Outside function"); console.log(x); Blocks only scope let and const declarations, but not var declarations.
Find elsewhere
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ scope-in-javascript-global-vs-local-vs-block-scope
Scope in JavaScript โ€“ Global vs Local vs Block Scope Explained
September 4, 2024 - Block scope is often confused with local scope, but there's a key distinction. In local scope, variables are typically defined within a function, while block scope is created within code blocks like if, for, or while statements.
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_scope.asp
JavaScript Scope
Scope determines the accessibility (visibility) of variables. ... Variables declared Globally (outside any block or function) have Global Scope.
Top answer
1 of 3
7
  1. javascript 5 does not use blocked scope it uses chained scope. the main difference is that you cannot access the variable out side of the scope unless you make it global. ES 6 will have blocked scope when you declare a variable with let.
  2. currently recommended to use var because ES 6 is not fully supported.
2 of 3
5

I'm not sure you really got your questions answered yet:

Is block scope sometimes the same as function scope? I know function scope is for everything inside a function, but don't get what exactly a block scope is.

Yes, a block scope is sometimes the same as a function scope. Block scope is everything inside a set of braces { a block scope here }. So, at the top of a function's code, a block scope will be the same as a function scope:

function test(x) {
   // this is both a block scope and a function scope
   let y = 5;
   if (x) {
       // this is a smaller block scope that is not the same as the function scope
       let z = 1;
   }
}

For Javascript, is it currently recommended to use let / const instead of var for future maintenance? (This was from Airbnb Style Guide)

let and const are part of the newest ES6 specification and are only implemented in the latest Javascript engines and sometimes in the latest engines they are only enabled with special flags. They are coming to all newer JS engines/browsers, but are not widely deployed yet. Thus, if you are writing Javascript for regular browser consumption across the broad internet, you cannot reliably use let and const yet.

There are some cases where you can safely program with let and const now:

  1. If you are targeting only a specific Javascript engine and you know that it has support for those features (such as a specific version of nodejs or a plug-in only for a specific version of a specific browser).

  2. If you are using a transpiler that will convert your code to code that will run in all browsers. When using a transpiler, you can write your code using the latest features and the transpiler will "dumb it down" so that your code will work in older browsers by using simulations of the newer features.

If you are programming for an environment where you know that let and const are supported, then it is advisable to use them as appropriate. If you declare a variable at the top of your function, then let and var will do the same thing.

If you declare a variable in a smaller scope within the function, then let will be contained within the smaller scope, but var will be hoisted to the top of the function and will have function scope, no matter where it is declared.


The AirBnb Style Guide you linked to is specifically written for an ES6 environment (note there is a separate link for an ES5 version of their style guide). So, that means that they are assuming an ES6 capable environment. That's either because they are targeting a server-side JS engine that they know supports ES6 or because they are using a transpiler that will convert ES6 code into something that will run on an ES5 engine.


A note about transpilers. Before using a transpiler and switching all variable declarations to let within block scopes, it is worth understanding what kind of code the transpiler generates and whether the extra code it generates has any effect on the performance of your application. For example, block scope for let is simulated by creating an inline IIFE which can lead to extra run-time overhead for every block that contains a let statement. I'm not saying this is necessarily a bad thing that should keep you from using a transpiler, but when deciding whether to use a transpiler, I'd suggest that you thoroughly familiarize yourself with what the transpiled code looks like for a variety of ES6 features so you know whether it is the right tool for any job you have or only for some jobs.

Top answer
1 of 1
8

In theory, function scope should actually be faster - variables are typically created in a stack frame, and function scope would only create that stack frame once, while block scope would need to repeadedly open up a new stack frame in every block.

In practice, there are several facts that invalidate that initial assumption:

  1. No compiler is forced to create a stack frame for a block only if a specific block is actually reached - And most compilers do exactly that - A stack frame is being created that holds room for the superset of all variables that are part of the function. Languages like C only define compile-time accessibility of a variable. So, the compiler must only make sure that access to a variable that is not currently in scope is forbidden - Not that this variable is not present at all. That is a rule that can be enforced at compile time. Note that good compilers can even re-use space in the stack frame that is used by variables with non-overlapping scope and will sort and consolidate all variables in a stack frame to ensure maximum memory re-use.
  2. Block scope can allow better usage of register variables if the compiler is clever enough and enough registers are available - Because variables in a block only need to have the lifetime of the block, they can be re-used earlier.

So, from a performance viewpoint, I don't actually see advantages for both approaches - As pointed out above, you can technically implement function scope even if the language asks for block scope. That might waste some memory, though.

From a programmer's standpoint, I do see, however, clear advantages for block scope (that might, however, just be because I grew up with languages like C and C++)

๐ŸŒ
DEV Community
dev.to โ€บ mingt โ€บ javascript-introduction-to-scope-function-scope-block-scope-d11
JavaScript: Introduction to Scope (function scope, block scope) - DEV Community
November 27, 2018 - The concept of block scope is introduced in ECMA script 6 (ES6) together with the new ways to declare variables -- const and let. Whenever you declare a variable in a function, the variable is visible only within the function. You can't access it outside the function.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ all-about-functions-and-scopes-in-javascript
All about Functions and Scopes in JavaScript - GeeksforGeeks
July 23, 2025 - Function scope: Variables that ... accessible anywhere inside the function. Block scope: Variable that is declared inside a specific block & can't be accessed outside of that block....
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-function-and-block-scope-in-javascript
What is function and block scope in JavaScript?
... When we run the above code, ... the function it is declared in. The block scope of a variable means that the variable is accessible within the block that is between the curly braces....
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ semantics function scope vs block scope
r/learnjavascript on Reddit: Semantics function scope VS block scope
November 2, 2022 -

So overall i understand the functionality behind block / function scope. But my questions seems more in line with the semantics of it.

Would a function scope not also be a block scope on top of being function scoped? Considering that it is contained within brackets. And variables inside it cannot be accessed from the outside unless passed via callbacks as arguments. The main difference that I can come to in my testing is that you can access variables inside block scope with VAR. But var cannot be used to access variables that are function scoped

const functionScope = () => {


if(x){
const variable = "This variable cannot be accessed outside this block"
var variable2 = "This variable can be accessed outside this block"
	// Inside these brackets is block scope
}

const variable = "This variable cannot be accessed outside this block"
var variable2 = "This variable cannot be accessed outside this block"
//inside these brackets is function scope
}
Top answer
1 of 3
2
Would a function scope not also be a block scope on top of being function scoped? Considering that it is contained within brackets. Are you saying that wherever we see {....} in JS, we need to consider it as "block scope"? If yes, that's not correct. For example, the {...} of an object literal doesn't create a "block scope." Keep in mind that "block scope" was introduced only in ES6, whereas {} was used for other purposes before ES6, and one such use was in the "signature of functions" to create function scope. As far as behaviour of var-declared variables vs let/const-declared variables, keep this in mind: var-declared variables "respect" only the {...} creating the function scopeโ€”other {...}s are invisible to them. This means that, even if we have 100 levels of "nested {}" inside a function and we have var x in the innermost {}, it will be scoped to the entire {} of the function definition. To quote from the MDN webdocs article on scope : Variables declared with var...do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. OTOH, from the same article By contrast, identifiers declared with let, const, and class do have block scope, meaning they "respect" any {...} that they find themselves in.
2 of 3
1
Yeah, sounds like you're just getting caught up on the fact that functions often use brackets. The brackets of a function are called the function body. Brackets used with things like for () {} or if () {} are called blocks. Overall there are 3 scopes: global, function, and bracket; and 4 ways to define/initialize variables: i = 0, var i = 0, let i = 0, and const i = 0. Initialization without var, let, or const becomes globally scoped no matter where it is initialized. With var you don't get block scope, but you do get function scope. let and const are both function and blocked scoped.
๐ŸŒ
DEV Community
dev.to โ€บ samabaasi โ€บ how-javascript-works-part-3-function-scope-block-scope-185n
๐Ÿš€How JavaScript Works (Part 3)? Function Scope, Block Scope - DEV Community
October 25, 2023 - Using meaningful names for your IIFEs improves code readability and debugging. Avoid anonymous function expressions, including IIFEs. When it comes to managing variable scope and preventing naming collisions, JavaScript provides a more robust solution known as block scoping.
๐ŸŒ
O'Reilly
oreilly.com โ€บ library โ€บ view โ€บ you-dont-know โ€บ 9781449335571 โ€บ ch03.html
3. Function Versus Block Scope - You Don't Know JS: Scope & Closures [Book]
The most common answer to those questions is that JavaScript has function-based scope. That is, each function you declare creates a bubble for itself, but no other structures create their own scope bubbles.
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ difference-between-block-scope-function-javascript-bbsedtech
Difference between block scope and function scope in JavaScript ?
August 28, 2023 - This means that the variable is ... Variables declared with var are not limited by block boundaries; they are hoisted to the top of the function, meaning they are available throughout the entire function's scope...