Functions in JavaScript – Declaration, Expression and Arrow Functions
Quick Answer: A function is a reusable block of JavaScript code. Function declarations, function expressions and arrow functions are three common ways to create functions. They differ in syntax, hoisting and how they handle this.
1. Why Do We Need Functions in JavaScript?
Imagine you manage admissions for a school with 1,000 students. Every student needs an admission summary. Each summary must show the student's name, class and admission status.
Would you write the same instructions 1,000 times? Think about how difficult that would become.
The problem without reusable functions
We can write the admission process directly for each student. The following example works, but repeats the same steps.
Example 1: Creating admission summaries without functions
const studentOne = { name: "Priya", grade: 8 };
const studentTwo = { name: "Arjun", grade: 9 };
const studentThree = { name: "Lakshmi", grade: 7 };
const summaryOne =
studentOne.name + " is admitted to grade " + studentOne.grade;
const summaryTwo =
studentTwo.name + " is admitted to grade " + studentTwo.grade;
const summaryThree =
studentThree.name + " is admitted to grade " + studentThree.grade;
console.log(summaryOne);
console.log(summaryTwo);
console.log(summaryThree);
Expected output
Priya is admitted to grade 8 Arjun is admitted to grade 9 Lakshmi is admitted to grade 7
Remember: This works, but it gets hard to manage. The same formatting logic appears in several places.
What goes wrong as the school grows?
- We repeat the same instructions for every student.
- A formatting change must be made in many places.
- One missed change can produce inconsistent summaries.
- Testing repeated code takes more effort.
Now think about 1,000 students. Small repeated tasks become difficult to maintain.
The solution with a function
Function = a reusable block of code that performs a task.
We write the summary logic once. Then we call it for each student.
Example 2: Reusing one function for all students
function createAdmissionSummary(student) {
return student.name +
" is admitted to grade " + student.grade;
}
const studentOne = { name: "Priya", grade: 8 };
const studentTwo = { name: "Arjun", grade: 9 };
const studentThree = { name: "Lakshmi", grade: 7 };
console.log(createAdmissionSummary(studentOne));
console.log(createAdmissionSummary(studentTwo));
console.log(createAdmissionSummary(studentThree));
Expected output
Priya is admitted to grade 8 Arjun is admitted to grade 9 Lakshmi is admitted to grade 7
Without functions vs with functions
| Without functions | With functions |
|---|---|
| Summary logic repeats for each student. | Summary logic is written once. |
| Changes must be repeated. | Changes happen in one place. |
| More code is needed for new students. | Call the same function with new data. |
| Repeated code is harder to test. | The reusable function can be tested separately. |
The idea to remember
- Function = reusable instructions for a task.
- Parameter = a named input received by a function.
- Argument = the actual value passed during a call.
- Return value = the result sent back by a function.
- Function call = running the function's instructions.
2. Three Ways to Create Functions in JavaScript
JavaScript supports several ways to create functions. Three common forms are declarations, expressions and arrow functions.
Use the function keyword. It can be called before its declaration.
Create a function and assign it to a variable.
Use the arrow syntax for concise function expressions.
Hoisting, this and constructor behavior differ.
3. Function Declaration in JavaScript
A function declaration creates a named function using the function keyword.
It is useful for named operations that you want to call throughout a scope.
Example 3: Function declaration for an admission summary
function createAdmissionSummary(studentName, grade) {
return studentName +
" is admitted to grade " + grade;
}
const summary = createAdmissionSummary("Priya", 8);
console.log(summary);
Expected output
Priya is admitted to grade 8
How does this declaration work?
functionstarts the function declaration.createAdmissionSummaryis the function name.studentNameandgradeare parameters.returnsends the generated summary back.- The function call passes
"Priya"and8as arguments.
Function declarations are hoisted
Hoisting = JavaScript makes certain declarations available before their written position.
Function declarations can be called before their declaration appears in the same scope.
Example 4: Calling a function before its declaration
const summary = createAdmissionSummary("Arjun", 9);
console.log(summary);
function createAdmissionSummary(studentName, grade) {
return studentName +
" is admitted to grade " + grade;
}
Expected output
Arjun is admitted to grade 9
Important: This behavior applies to function declarations. It does not mean every function expression can be called before initialization.
4. Function Expression in JavaScript
A function expression creates a function as part of an expression. We often assign it to a variable.
Function expression = a function value stored or used like other values.
The function can have a name, but anonymous expressions are also common.
Example 5: Assigning a function expression to a variable
const createAdmissionSummary = function(studentName, grade) {
return studentName +
" is admitted to grade " + grade;
};
const summary = createAdmissionSummary("Lakshmi", 7);
console.log(summary);
Expected output
Lakshmi is admitted to grade 7
How does a function expression work?
constcreates a variable binding.- The function expression creates the function value.
- The variable stores a reference to that function.
- We call the function through the variable name.
- The function returns the admission summary.
Can we call it before the assignment?
No. A const variable cannot be accessed before initialization.
Example 6: A function expression called too early
createAdmissionSummary("Priya", 8);
const createAdmissionSummary = function(studentName, grade) {
return studentName +
" is admitted to grade " + grade;
};
Result: JavaScript throws a ReferenceError. The variable is in its temporal dead zone until initialization.
5. Arrow Functions in JavaScript
An arrow function is a shorter way to write a function expression.
It uses the => symbol. This symbol is called the arrow.
Arrow functions are common in callbacks, array methods and short operations.
Example 7: Creating an admission summary with an arrow function
const createAdmissionSummary = (studentName, grade) => {
return studentName +
" is admitted to grade " + grade;
};
console.log(createAdmissionSummary("Priya", 8));
Expected output
Priya is admitted to grade 8
Arrow functions with one parameter
Parentheses are optional when there is exactly one simple parameter.
Example 8: One parameter without parentheses
const getStudentLabel = studentName => "Student: " + studentName;
console.log(getStudentLabel("Arjun"));
Expected output
Student: Arjun
Arrow functions with no parameters
Use empty parentheses when the function receives no parameters.
Example 9: Arrow function without parameters
const getSchoolName = () => "Green Valley School";
console.log(getSchoolName());
Expected output
Green Valley School
Implicit return in arrow functions
An expression body returns its result automatically. You do not need the return keyword.
Example 10: Returning a value without writing return
const calculateAdmissionFee = (tuitionFee, activityFee) =>
tuitionFee + activityFee;
console.log(calculateAdmissionFee(12000, 1500));
Expected output
13500
Remember: An arrow function with curly braces needs an explicit return when it should return a value.
Example 11: Curly braces need an explicit return
const calculateAdmissionFee = (tuitionFee, activityFee) => {
return tuitionFee + activityFee;
};
console.log(calculateAdmissionFee(12000, 1500));
Expected output
13500
6. Professional Function Flow Animations
These diagrams show how each function form works. Each animation follows a different flow. The text stays static and readable while the active node changes.
Animation 1: Function Declaration
A named function is available for calls within its scope.
Animation 2: Function Expression
The function value is created and assigned to a variable.
Animation 3: Arrow Function
The arrow function receives input and returns a concise result.
The three animations show declaration and calling, variable assignment, and arrow-function execution. They cycle automatically when the diagrams are visible.
7. Function Declaration vs Expression vs Arrow Function
| Feature | Declaration | Expression | Arrow |
|---|---|---|---|
| Syntax | function name() |
const name = function() |
const name = () => |
| Hoisting | Can be called before declaration in its scope. | Cannot access the variable before initialization. | Cannot access the variable before initialization. |
Own this |
Yes, based on how it is called. | Yes, based on how it is called. | No. It uses lexical this. |
| Constructor | Can be used with new when constructible. |
Can be constructible when it is a normal function. | Cannot be used with new. |
| Best fit | Named reusable operations. | Functions assigned or passed as values. | Callbacks and concise operations. |
8. Understanding the this Keyword
this = a value determined by the function's calling context, or its lexical environment.
Normal functions get their own this value. Arrow functions do not create their own.
Consider a school object. We want to display its name.
Example 12: A normal method uses its calling object
const school = {
name: "Green Valley School",
showName: function() {
return this.name;
}
};
console.log(school.showName());
Expected output
Green Valley School
Here, this refers to the object before the method call.
Now look at an arrow function used as an object method.
Example 13: An arrow function does not get its own this
const school = {
name: "Green Valley School",
showName: () => {
return this.name;
}
};
console.log(school.showName());
Expected output
undefined
In this example, the arrow function uses the surrounding this. It does not use the school object as its own this.
Best practice: Avoid arrow functions as object methods when the method needs the object through this.
9. Where Do Developers Use Each Function Type?
Function declarations for named operations
Use declarations for reusable operations with clear names. They are also useful when a function is called earlier in its scope.
Function expressions for assigned behavior
Use expressions when a function is stored in a variable or passed to another function. They are useful when you want a function value.
Arrow functions for callbacks
Callback = a function passed to another function for later execution.
Array methods such as map(), filter() and forEach() often use arrow functions.
Example 14: Using an arrow function with map
const students = [
{ name: "Priya", grade: 8 },
{ name: "Arjun", grade: 9 },
{ name: "Lakshmi", grade: 7 }
];
const studentNames = students.map(student => student.name);
console.log(studentNames);
Expected output
[ 'Priya', 'Arjun', 'Lakshmi' ]
map() creates a new array from the returned values. Each arrow function call returns one student's name.
10. Common Mistakes and Best Practices
Mistake 1: Calling a const function expression too early
Wrong: Calling the function before its variable is initialized.
createAdmissionSummary("Priya", 8);
const createAdmissionSummary = function(name, grade) {
return name + " - " + grade;
};
Correct: Initialize the variable before calling it.
const createAdmissionSummary = function(name, grade) {
return name + " - " + grade;
};
console.log(createAdmissionSummary("Priya", 8));
Rule: A function expression assigned to const must be initialized first.
Mistake 2: Forgetting return in a block-bodied arrow
Wrong: Curly braces do not return a value automatically.
const calculateFee = (tuition, activity) => {
tuition + activity;
};
Correct: Write return, or use an expression body.
const calculateFee = (tuition, activity) => {
return tuition + activity;
};
Rule: Use explicit return inside a block body.
Mistake 3: Using arrow functions for methods that need this
Wrong: An arrow function does not bind its own this.
Correct: Use method syntax or a normal function when you need dynamic this.
const school = {
name: "Green Valley School",
showName() {
return this.name;
}
};
Rule: Choose the function form based on its behavior, not only its length.
Mistake 4: Confusing parameters and arguments
Wrong idea: Treating the names in a function definition as passed values.
Correct idea: Parameters are names. Arguments are values supplied during a call.
function showStudent(studentName) {
console.log(studentName);
}
showStudent("Priya");
Rule: studentName is the parameter. "Priya" is the argument.
11. How This Topic Comes Up in Interviews
Question 1: What is the difference between a declaration and an expression?
What the interviewer wants: They want to check your understanding of hoisting and initialization.
Strong answer: “A function declaration is available before its written position in the same scope. A function expression is assigned to a variable. That variable must be initialized before we call it. I use declarations for named operations and expressions when I need a function value.”
Question 2: How are arrow functions different from normal functions?
Strong answer: “Arrow functions provide shorter syntax. They do not create their own this. They also cannot be used as constructors. I often use them for callbacks. For school object methods that need the school through this, I use normal method syntax.”
Question 3: What is an implicit return?
Strong answer: “An arrow function can return an expression without writing the return keyword. This works when we use an expression body. If we add curly braces, we must write return when we need a result.”
Question 4: Can an arrow function be used with new?
Strong answer: “No. Arrow functions are not constructible. JavaScript throws a TypeError if we try to use an arrow function with new.”
What interviewers may expect at different levels
- Junior: Explain the syntax and write each function form.
- Mid-level: Explain hoisting, return behavior and callback usage.
- Senior: Explain lexical
this, scope and function behavior. - Architect: Choose clear function styles and explain maintainability trade-offs.
12. Hands-On Practice
Beginner: Create a student greeting
Write a function declaration named createGreeting. It should accept a student name and return a greeting.
Expected result: Calling it with "Priya" should return "Welcome, Priya".
Intermediate: Calculate the school fee
Write a function expression named calculateTotalFee. It should accept tuition and activity fees.
Expected result: Inputs of 12000 and 1500 should return 13500.
Advanced: Filter students by grade
Create an array of students with names and grades. Use filter() with an arrow function. Return only students in grade 8 or above.
Hint: Your callback should check student.grade >= 8.
Challenge: Compare all three forms
- Create the same admission summary using a declaration.
- Rewrite it as a function expression.
- Rewrite it again as an arrow function.
- Call all three with the same student details.
- Compare the returned values.
13. Frequently Asked Questions
Can a function declaration be called before it is written?
Yes. Function declarations are hoisted within their scope. You can call them before their declaration statement.
Are function expressions hoisted?
The variable declaration follows its own hoisting rules. However, a function expression assigned to const or let cannot be called before initialization.
Do arrow functions have their own this?
No. They use this from the surrounding lexical environment.
Can arrow functions have multiple parameters?
Yes. Use parentheses around multiple parameters. For example, (tuition, activity) => tuition + activity.
When should I use an arrow function?
Use arrow functions for callbacks and short operations. Avoid them as methods when you need a method's own this.
Can a function return more than one value?
A function returns one value. You can return an object or array containing several values.
14. Next Steps and Community
You now understand three common ways to create JavaScript functions. Practice each form with real application examples.
- Write one function declaration without looking at the example.
- Convert the same function into a function expression.
- Rewrite it using arrow function syntax.
- Test how each form behaves with different inputs.
- Practice explaining hoisting and lexical
this.
Explore further: Read the official MDN JavaScript Functions Guide for more details.
Share your knowledge: Share your examples and discuss different approaches with other learners. Your explanation may help someone understand functions more clearly.
Keep practising, keep building and keep improving your JavaScript skills.
Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.