Skip to main content

Command Palette

Search for a command to run...

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

Updated
•6 min read•View as Markdown
Function Declaration vs Function Expression: What’s the Difference?

Welcome to the JavaScript blog series. Hope you are liking the previous blogs.

This time, we have something fundamental to every programming language: functions.

We will cover here everything about functions, except arrow functions. We have a separate blog for it. So, let's begin

Functions in JavaScript

What are functions?

To define it formally, we say it is a piece of code that is reusable (can be used multiple times) and performs a certain action.

Problem: I want to write a program that can add two numbers.

Let's learn to declare a function, then we will continue with the problem.

How to declare functions in JavaScript?

A function is a set of instructions that takes input and produces or returns a value or data.

What do we need to declare a function?

  1. Name of the function

  2. Parameters (input)

  3. 'function' keyword

  4. set of instructions

function add(a + b){ //Taking two values
    const sum = a + b; //adding two values & storing to sum
    
    return sum //returning sum
}

This is called a function declaration.

Earlier, I said that a function is a piece of code that is reusable (can be used multiple times) and performs a certain action. Let's prove it.

To utilise a function, we need to call it. What in this world does calling a function mean?

It just means calling a person who can do a certain task for you. For example, calling a plumber to check leakages in the pipe.

Similarly, we have a person whose name is add It tells you the sum of two numbers whenever you call it.

add(4,6) //returns us 10
add(4,16) //returns us 20
add(14,6) //return, we guess
//I have showed you principle of reusability.
// I have added two number three times without repeat code. 

What if functions were not there?

let a = 4
let b = 6
sum = a + b

// sum of 16 and 4
let a = 4
let b = 16
sum = a + b

//see we are repeating code for doing same task, that is of adding two numbers
Default parameter

It provides the value of the parameter in case the user/coder doesn't provide it upon calling.

function sayHello(name="JavaScript"){
    return `Hello from ${name}`
}

console.log(sayHello("Arjun")); //Hello from Arjun console.log(sayHello()); // Hello from JavaScript

Types of function
//Type 1: No input, only Output
function hello()
{
return "Hello World"
}

//Type 2: No input, no output function fun() { console.log("Have Fun") } //IMP - This is not output, output means function return some value.

//Type 3: Both Input and Output function add(a,b) { return a + b }

//Type 4: Only input No Output function add(a,b) { const sum = a + b }

More about the return keyword

It had troubled me a lot. I hope it doesn't bother you.

return The keyword has two works.

1. First, it gives value to function; by this means, what does value contain?

Just like a variable has some value, a function also has some value.

Whatever it returns is its value?

let num = 5 //here num has value '5'

function sum(a,b) { return a + b }

let total = sum(4,6) //sum makes it's value equal to total. now value of sum equal to value of total.

console.log(total) // output - 10 console.log(sum(4,6)) //output - 10

2. Another work is to stop the execution of the function. It makes the function quit.

function add(a,b)
{
sum = a + b
return "I stopped function" //Dukaan Band! Function Stopped!
console.log(sum) // It will never reach here
}

Function expression

It is another way to declare a function. That's it

First, let's understand an anonymous function. Just like an anonymous person doesn't have a name, you can't call him/her.

function(a,b)
{

return a + b

}

Although it is a function, it can't be called or accessed. because we have no access to its memory. Just like if we don't know a person's address or phone number, we can't call him same is the case with the anonymous function.

There are so many applications to anonymous functions. Tell you in later blogs

Problem: We can't access an anonymous function because we lack its location/memory address.

Solution: Let's store it in a variable.

Function expression syntax

const add = function(a,b) //stored variable in add variable
{
return a + b
}

Difference between declaration and expression.

You can't call a function expression before their decalaration. Let's see an example

console.log(add(4,5)) //Called function declaration
function add(a,b)
{
return a + b
}

console.log(sub(9,4)) //This is wrong you are called it before declaration

let sub = function(a,b)
{
return a - b
}

console.log(sub(9,4)) //This is correct


//It happens because of blunder

Hoisting: The cause of the blunder

Very, very hard to understand, but let's get it the easy way.

I want you to search, hoisting the meaning in the vocab. It is to raise or uplift something.

When JavaScript runs the code, it has two phases or steps.

  1. Creation Phase (here hoisting happens)

  2. Execution Phase (Not today)

Creation Phase

In this phase, memory is allocated for each variable, and they are raised in code (known as hoisting). This only happens to variable declarations and functional declarations.

What we write:

console.log("Function Declaration")
add()
let name = "Rahul"
function add(a,b)
{
return a + b
}
let age = 45

How JavaScript sees it in the creation phase.

//Hoisted Code
let name;
let age;
function add()
{
return a + b
}

//-------------------------------------------------------------------------
console.log("Function Declaration")
add(4,8) //As we can sees declaration goes above all. This doesn't happens in function expression
name = "Rahul"
age = 45

Let's also use a function expression.

add(5,6)
let name = "Rahul"
let add =  function(a,b)
{
return a + b
}
let age = 45

Now, how JavaScript sees it

//Hoisted code
let name;
let add;
let age;

//-------------------------------------------------------------------------
add(5,6) //Gives error because it is not declared yet in memory
name = "Rahul"
add =  function(a,b)
{
return a + b
}

add(9,1) //This is correct, because it is declared
age = 45

Which one to use when?

It's all about what you care about.

Function Declaration Function Expression
Access before declaration Access only after declaration
Not suitable for Callbacks Suitable for Callbacks
Not suitable for IIFE Suitable for IIFE
Faster loading before anything else Loads when the interpreter reaches a line of code

Conclusion:

If you have any doubt, do let me know in the comments.

27 views

Javascript

Part 4 of 25

In this series, I will cover javascript in very simple way with code examples and also reasons. It will cover from basics to advanced. 1. variables & data types and conversions 2. operators 3.control flow 4. function and types 5. Arrays 6. Arrays methods 7. Objects and OOPS 8. Magic of this 9. Promises 10. Dates 11. Other low level concepts (closures, queues, hoisting etc) 12. asynchronous programming etc

Up next

Arrow Functions in JavaScript: A Simpler Way to Write Functions

Welcome to the JavaScript Blog Series Arrow functions in JavaScript As the title of the blog suggests, it is a short and easier way to write a function. It is more related to function expression than

More from this blog

P

Programming for Babies

54 posts

Documenting my learning journey in a developer cohort. Topic-wise blogs for beginner developer on software development, sharing how I learn, mistakes, tips, problem-solving, mindset and real projects.