Sobes.tech
Middle+

What is the difference between a function expression and a function declaration?

sobes.tech AI

Answer from AI

Function Declaration is a function definition using the function keyword at the beginning:

function greet() {
  console.log('Hello');
}

Function Expression is assigning a function to a variable:

const greet = function() {
  console.log('Hello');
};

Main differences:

  • Hoisting: Function Declaration is hoisted to the top of its scope, so it can be called before its declaration. Function Expression is not hoisted, so it can only be called after the assignment.

  • Function name: Function Declaration always has a name. Function Expression can be anonymous or named.

  • Usage: Function Expression is often used to pass functions as values, for example, in callbacks.

Hoisting example:

sayHi(); // works
function sayHi() { console.log('Hi'); }

sayBye(); // error
const sayBye = function() { console.log('Bye'); };
What is the difference between a function expression… - sobes.tech