🟢 EasyFunctions📖 Theory Question

What is the difference between function declarations and function expressions?

💡

Hint

Declarations are hoisted fully; expressions are not — and expression form gives more control

Full Answer

Both create functions but behave differently with hoisting and syntax.

// Function Declaration — hoisted completely (name + body)
greet(); // ✅ works BEFORE the declaration
function greet() { return 'hello'; }

// Function Expression — NOT hoisted as a function
sayHi(); // ❌ TypeError: sayHi is not a function (var hoisted as undefined)
var sayHi = function() { return 'hi'; };

// Arrow function expression
const add = (a, b) => a + b;

// Named function expression (NFE) — name only visible inside
const fact = function factorial(n) {
  return n <= 1 ? 1 : n * factorial(n - 1); // factorial = self
};
console.log(typeof factorial); // undefined — not accessible outside

When to prefer each:

  • Declaration — top-level utility functions, when you want full hoisting
  • Expression — callbacks, conditional function creation, storing in variables, passing as args
💡 Most style guides prefer expressions (especially arrow) for callbacks and class methods. Declarations are fine for named utility functions at module scope.

More Functions Questions

🟢 EasyWhat is the difference between call, apply, and bind?🟢 EasyHow do arrow functions differ from regular functions?🟢 EasyWhat is a pure function and why does it matter?🟢 EasyWhat are Higher-Order Functions (HOF)?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint