Skip to main content

Command Palette

Search for a command to run...

Function Declaration vs Function Expression

Updated
2 min readView as Markdown

Functions-
functions enclose a piece of code within them that perform a certain task.
They provide us with the following :-

  • Enclose a block of code inside a reusable unit

  • Keep code cleaner and organized

  • Avoid repetition (DRY principle – Don’t Repeat Yourself)

  • Improve readability and maintainability

  • Reuse logic multiple times

Write once , use many times


Function declaration

A function declaration defines a named function using the function keyword.

function getSum(a, b) {
  console.log("sum: " + (a + b));
}

getSum(2, 4);  // function call
  • getSum is the function name

  • a and b are parameters (inputs to the function)

  • {} contains the block of code that runs when the function is called

  • getSum(2, 4) is the function call, where 2 and 4 are arguments

Returning a value

Instead of just printing the result, we can return it using the return keyword.

function getSum(a, b) {
  return a + b;
}

const sum = getSum(2, 4);
console.log(sum);  // 6
  • return sends the result back to where the function was called

  • It allows us to store the result in a variable

  • The function stops executing once return runs

  • sum will hold the value returned by getSum function.

Function Expression

A function expression stores a function inside a variable.

const addition = function getSum(a, b) {
  return a + b;
}

getSum();

Here:

  • The function is assigned to a variable

  • The variable name is used to call the function

Difference between declaration and expression

Hoisting -
Declaration syntax - The declaration syntax gets hoisted i.e the function can be called even before its declared, lifted by javascript to the top of the file before running.

Expression syntax (NOT Hoisted) - since in this syntax , the function will be held inside a variable. It won't be executed until execution reaches that line

// declaration
sayHi();  // works
function sayHi() { console.log("Hi!"); }

// expression
sayBye(); // crash
const sayBye = function() { console.log("Bye!"); };

Usage

Declaration

want a global function that can be used anywhere

Expression

want to keep code structured, scoped, or passed into other functions.