Skip to main content

Command Palette

Search for a command to run...

Function Declaration vs Function Expression: What’s the Difference?

Updated
3 min readView as Markdown
D

I am a developer learning web development , I am a college dropout pursuing my passion in software field

In JS functions are the building blocks, Thinks of them as a reusable piece of code block that once created then it can be used any number of time and anywhere in the entire codeBase

There are many ways to declare a function in JS
at first u may think why we need so many ways to do the same thing, but belive me by the end of this blog u will understand that they all serve different work

What Are Functions and Why Do We Need Them?

A function is just a reusable block of code that is designed to perform a specific task. And return us a value
Example:

Here in the above example
'add' is the name of the function
a and b are inputs to the function ( technically called a arguments)
While calling the function add we are passing the value of the arguments ( arguments)
return a + b gives the result that we have printed using console
Now instead of writing a + b everywhere we can just call the function add with new arguments

Function Declaration

A function declaration defines a named function using the function keyword, followed by the name of the function and its parameters.

Syntax :

Example :

Function Expression

A function expression involves storing a function inside a variable. These functions can be named, but they are most commonly written as "anonymous functions" (functions without a name).

Syntax:

Example:

Function Declaration vs Function Expression

A High-Level Look at Hoisting

Hoisting is how JavaScript "moves" declarations to the top of their scope before the code actually executes.

  • Function Declarations are fully hoisted. This means you can call the function before you define it in your code, and it will work perfectly.

  • Function Expressions are not hoisted in the same way. Because they are assigned to variables, the engine knows the variable name exists, but it doesn't know it's a function until that line of code is reached. Trying to call it early will result in an error.

When Should You Use Each?

Both approaches are useful depending on the situation.

Use Function Declarations When

  • You want reusable utility functions

  • The function should be available throughout the file

  • You want clearer and simpler code structure

Use Function Expressions When

  • You want to store functions inside variables

  • You want to pass functions as arguments

  • You are working with callbacks or functional programming patterns