How many scopes are in this code block?

I said 4 (explained below) but this was marked wrong. Can anyone tell me what the correct answer is? Thanks

let a;

function func1() {
  const b = 1;
  function func2() {
    const func3 = c => c + 5;

  const func4 = function() {

// My Answer (marked wrong)
There are 4 scopes present. a is initialized on the global
 scope. func1() creates a function scope. Technically it is
 also a block scope. function func2 creates another block
 scope for its function body. function func4 creates yet
 another separate block scope for its function body.
 Demonstrated here are the different levels of scopes.

Its hard to give hints without giving the answer. The devil is in the details, but you’re on the right track. Each function creates a scope.

Are there 5 scopes?

I just saw that there is another function func3() with its own scope

Yep, you missed func3, which has its own scope. To be fair, I missed it too until you pointed it out.

Also, function scope is not quite block scope. Vars declared with var are hoisted out of any block scope to the top of the enclosing function scope. To wit:

function foo() {
   { var a = 123; }

Edit: Sorry, I should say that var gets hoisted into the enclosing function scope, but not to the top: they will remain undefined until they actually get assigned to. Functions declared with function are indeed hoisted to the top, which is why you can define functions after the code that calls them.

1 Like