Why does this JavaScript code return an error?

Viewed 57

I know in JavaScript only function declarations are hoisted, which means it should print 30 after running the function sum.

However it says diff is not defined, shouldn't it be hoisted?

sum(10, 20);
diff(10, 20);
    
function sum(x, y) {
  return x + y;
}
    
let diff = function(x, y) {
  return x - y;
} 

5 Answers

Yes, let and const are hoisted but you cannot access them before the actual declaration is evaluated at runtime.

You are accessing the function before you initialize it.

So this should work,

let diff = function(x, y) {
  return x - y;
} 

function sum(x, y) {
  return x + y;
}

console.log(sum(10, 20));
console.log(diff(10, 20));

let diff will hoist but at the moment when function diff(10, 20); will be called variable diff will not jet be defined with the function. Google this topic function declaration vs function expression

It's because as you said, only function declarations are hoisted, not function expressions (assigning a nameless function to a variable). Following code works:

sum(10, 20);
diff(10, 20);
    
function sum(x, y) {
  return x + y;
}
    
function diff(x, y) {
  return x - y;
} 

To declare diff the way you did, you must lift it to the top of your code:

let diff = function(x, y) {
  return x - y;
} 

sum(10, 20);
diff(10, 20);
    
function sum(x, y) {
  return x + y;
}
    

Because Function Expressions are not hoisted like Function Declarations

Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you create them:

console.log(notHoisted) // undefined
//  even though the variable name is hoisted, the definition isn't. so it's undefined.
notHoisted(); // TypeError: notHoisted is not a function

var notHoisted = function() {
   console.log('bar');
};

https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function#function_expression_hoisting


You will need to use a Function Declaration if you want it to be hoisted.

Related