Sobes.tech
Junior

What is the difference between two ways of declaring a function?

sobes.tech AI

Answer from AI

Function Declaration and Function Expression.

Property Function Declaration Function Expression
Hoisting Is hoisted (available before its declaration in code). Is not hoisted (not available before its declaration).
Syntax Declared as a standalone statement. Declared as part of an expression (e.g., assignment or argument).
Example function myFunction() {} const myFunction = function() {}; or const myFunction = () => {};
Usage Preferred for named standard functions. Often used for anonymous functions passed as callbacks.
Scope Available throughout its containing block or script/module. Scope depends on the expression it is part of.
// Example of Function Declaration
function sayHelloDeclaration() {
  console.log('Hello from Declaration');
}

sayHelloDeclaration(); // Can be called before declaration thanks to hoisting

// Example of Function Expression
const sayHelloExpression = function() {
  console.log('Hello from Expression');
};

sayHelloExpression(); // Can only be called after declaration

// const sayHelloArrow = () => { // Arrow function example (also a Function Expression)
//   console.log('Hello from Arrow Function');
// };