Aditya Singh Aditya Singh - 6 months ago 14
Javascript Question

Why are callback functions not hoisted in JavaScript?

I understand the concept of variables and function declaration in JavaScript being hoisted at the top of the enclosing scope. But if I have a named callback function, its not being hoisted. I am not able to understand why is that so. I have the code in the below link explaining the scenario

Example:

function enclosingScope () {
var b;

function inner (def) {
def();
}
var a = 2;
}

// After hoisting due to compilation, the above changes to
function enclosingScope () {
// Function declarations are hoisted before variables
function inner (def) {
def();
}

var b, a;
a = 2
}

// But if I have a named callback, will that be hoisted?
function enclosingScope () {
function inner (def) {
def();
}

var b, a;
a = 2

inner(function cb () {
console.log('Test callback hoisting')
})
}

Answer

The behavior in question is not limited to named callbacks. It's the way any named function expression works. Consider the following:

function foo() {
  (function baz() { });
  console.log(typeof baz);
}

> foo()
< undefined

baz is not accessible outside its body. So this is a different issue than hoisting.