I would like to ask how to explain this (javascript function)

I believe it should be because of lexical scoping or static scoping along with function scoping.

lexical scoping says variable scope is dependent on when the function was created in your cases when function b was created num was scoped to global.

function b() {
 console.log(num)//num is scoped to its parent function it was created in

function a() {
  var num = 3;//b will not have access to this num since it was not created here
 num = 1;

But if it were dynamic scoping then a variables scope is based on order of execution in which case num would have been scope to the caller a’s num.

if you try this snippet then it will correctly print 3.

function a(cb) {
  function b() {
  }//b is created here so it has access to num
 var num = 3;
num = 1;

You can read about static scoping and dynamic scoping in this question where static vs dynamic, function vs block scope is explained better.

Leave a Comment