Hadoren
Hadoren

Reputation: 165

JavaScript Hoisting: Function Can Refer to Another Function Declared Below It?

I have:

// Shouldn't we have the following hoisted?
// var multiply; (undefined)
// var add; (undefined)

var multiply = function(num) {
  return add(num) * 2;
};

var add = function(num) {
  return num + 1;
};

console.log(multiply(1)); // No error, somehow "multiply" calls "add"!

I thought that JavaScript variables are hoisted to the top, but not the values that they are assigned to. Somehow multiply calling add doesn't return an error, even though add is declared below multiply.

Upvotes: 1

Views: 61

Answers (1)

Half
Half

Reputation: 5508

You are correct in that the declarations are hoisted to the top, while the assignments are not.

However, functions don't keep the values of any variables outside of them from when they are created. Instead, they use whatever is in them when they are called. In this case, add is undefined when the multiply function is created, but is assigned a function before multiply is called, so multiply uses the new assigned function.

To see this more clearly, consider this code:

var multiply = function(num) {
    return add(num) * 2;
};

// Would be an error
// console.log(multiply(1));

var add = function(num) {
    return num + 1;
};

console.log(multiply(1)); // Prints 4

add = function(num) {
    return num + 2;
};

console.log(multiply(1)); // Prints 6

The last console.log prints 6 because multiply used the new function in add instead of keeping the one it had before.

Upvotes: 1

Related Questions