1

My question is why the following code prints 1 instead of 500; When the callback is invoked and it doesnt find the variable count, doesnt it first looked at the context of func1 ?

function func1(cb){
  let count = 500
  cb()
}


let count = 1

function func2() {
  console.log(count);
}


func1(func2) 
sco
  • 367
  • 3
  • 14
  • 1
    You are confusing the runtime notion of scope (dynamic) with the compile-time notion of scope (lexical). When you call `cb()` the engine looks through the lexical scopes the function was defined in, not the runtime call stack. – Jared Smith Aug 13 '18 at 19:19

3 Answers3

0

Let is the scope variable. And in func1 it’s just function scope variable. You should use one global scope variable instead of creating new one.

0

That's a matter of scopes, the first count hasn't the same scope of the second one, different is this:

    let count = 1
    
    function func2() {
      console.log(count);
    }
    
    
    function func1(cb){
      count = 500
      cb()
    }

    func1(func2)

There you got what you spected,

And also, if you do:

    let count = 1
    
    function func2() {
      console.log(count);
    }
    
    
    function func1(cb){
      let count = 500
      cb()
    }
    func1(func2) 

You are creating a new variable count, with different scope of the first count, meaning, it will print 1

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
0

1. func1(func2)

You are passing a function func2 as an argument to the func1

2. let count = 1

You have declared global variable

3. You have passed the func2 to func1 as argument but you have done nothing there. You have declared the variable inside the function but still it is out of the scope of func2

function func1(cb){
  let count = 500
  cb()
}

4. func2 only know the global count variable so it will console 1 instead of local variable of func1

function func2() {
  console.log(count);
}
Sujan Gainju
  • 4,273
  • 2
  • 14
  • 34