Difference Between Function Declaration and Function Expression

Difference Between Function Declaration and Function Expression

We will try to understand the difference between function Declaration and Function Expression .

Function Declaration and Function Expression are two ways to define functions in JavaScript. They differ in how they are declared and how they are hoisted within the code.

  1. Function Declaration: A function declaration is a statement that defines a named function and makes it available in the current scope. It follows the syntax:

function functionName(parameters) {
  // function body
}

Key points about function declarations:

  • They are hoisted: Function declarations are hoisted to the top of the current scope. This means you can use the function before its actual declaration in the code.

  • They have a named identifier: The function name is mandatory and should be used to invoke the function.

sayHello(); // Output: "Hello!"

function sayHello() {
  console.log("Hello!");
}

sayHello(); // Output: "Hello!"
//  In Console Two Times "Hello!" will print because we called the function Two times .
  1. Function Expression: A function expression assigns a function to a variable or a property of an object. It follows the syntax:

var variableName = function(parameters) {
  // function body
};
// Another Example of function Expression is 
let sayBye = function() {
 console.log("Bye Bye");
}

Key points about function expressions:

  • They are not hoisted: Function expressions are treated like regular variable assignments, so they are not hoisted. You can only use them after the assignment.

  • They can be anonymous or named: You can choose to provide a name for the function or leave it anonymous.

sayBye();   // Here Error will come   
let sayBye = function() {
    console.log("Bye Bye")  //  this is the function expression
}
sayBye();   // OutPut =>  Bye Bye

// Let me show you the error so keep in the mind function expression will be treated like a variable 

sayBye();
^

ReferenceError: Cannot access 'sayBye' before initialization
    at Object.<anonymous> (/tmp/QfUWfglX0A.js:11:1)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47

In summary, the main differences between function declarations and function expressions are hoisting behavior and the requirement of a function name. Function declarations are hoisted and require a name, while function expressions are not hoisted and can be anonymous.