I'm currently learning JavaScript and recently spent some time understanding functions. While studying, I created these notes covering function declarations, parameters, arguments, return statements, function expressions, arrow functions, and commonly used built-in methods. Sharing them here in case they help fellow beginners on their JavaScript journey.
What is a Function?
A function is a reusable block of code designed to perform a specific task.
Think of a function like a machine:
- You give some input.
- The machine processes it.
- It gives back an output.
For example, a calculator's addition operation behaves like a function:
10 + 20 = 30
In JavaScript:
function add(a, b) {
return a + b;
}
Here:
- a and b are inputs.
- The function performs addition.
- The result is returned.
Functions help us avoid writing the same code repeatedly.
Why Do We Need Functions?
Imagine you need to display a welcome message 100 times.
Without functions:
console.log("Welcome");
console.log("Welcome");
console.log("Welcome");
console.log("Welcome");
This quickly becomes difficult to maintain.
With a function:
function welcome() {
console.log("Welcome");
}
welcome();
welcome();
welcome();
Benefits:
- Less code
- Better readability
- Easier maintenance
- Improved reusability
Real-Life Example
Suppose you're building an e-commerce application.
Every time a customer places an order, you may need to:
- Calculate total price
- Apply discounts
- Calculate taxes
- Generate invoices
Instead of writing the same logic repeatedly, you can create functions:
calculateTotal();
applyDiscount();
calculateTax();
generateInvoice();
Functions make large applications easier to organize and maintain.
Rules for Naming Functions
A function name should clearly describe what the function does.
Good Examples
function calculateSalary() {}
function getUserData() {}
function printInvoice() {}
function findLargestNumber() {}
Poor Examples
function a() {}
function xyz() {}
function temp() {}
Naming Rules
A function name:
✔ Can contain letters
✔ Can contain numbers (but not at the beginning)
✔ Can contain _ and $
✔ Should start with a letter
Valid Names
function add() {}
function add123() {}
function user_data() {}
function $calculate() {}
Invalid Names
function 123add() {}
function my-name() {}
function function() {}
Anatomy of a Function
function add(a, b) {
return a + b;
}
Function Keyword:
function
Tells JavaScript you're creating a function.
Function Name:
add
Used to call the function.
Parameters:
(a, b)
Inputs accepted by the function.
Function Body:
{
return a + b;
}
Contains the logic that gets executed.
Calling a Function
Creating a function does not execute it.
function greet() {
console.log("Hello");
}
Nothing happens until you call it:
greet();
Output:
Hello
This process is called function invocation or function calling.
Parameters vs Arguments
This is a common source of confusion for beginners.
Parameters
Variables declared in the function definition.
function add(a, b)
Here a and b are parameters.
Arguments
Actual values passed when calling the function.
add(10, 20);
Here 10 and 20 are arguments.
Easy way to remember:
Parameters = Placeholders
Arguments = Actual Values
Is return Mandatory?
No.
A function can work without a return statement.
function greet() {
console.log("Hello");
}
This function simply prints output and does not return anything.
What Does return Do?
The return keyword sends a value back to the place where the function was called.
Example:
function add(a, b) {
return a + b;
}
let result = add(10, 20);
Internally, JavaScript treats it like:
let result = 30;
because:
add(10, 20)
returns:
30
Difference Between console.log() and return
Many beginners assume they serve the same purpose.
They do not.
console.log()
function add(a, b) {
console.log(a + b);
}
Purpose:
Display information in the console.
Output:
30
However, the value cannot easily be reused.
return
function add(a, b) {
return a + b;
}
Purpose:
Send a value back to the caller.
Now the value can be:
- Stored in a variable
- Reused later
- Passed to another function
- Sent to a database
- Displayed in the UI
Why is return Preferred?
Using console.log():
function add(a, b) {
console.log(a + b);
}
The value is displayed, but not reusable.
Using return:
function add(a, b) {
return a + b;
}
let total = add(10, 20);
console.log(total * 2);
Output:
60
This flexibility is why professional developers use return extensively.
Function Declaration
Traditional way of creating functions.
function add(a, b) {
return a + b;
}
Function Expression
A function stored in a variable.
const add = function(a, b) {
return a + b;
};
Arrow Function
Modern syntax introduced in ES6.
const add = (a, b) => {
return a + b;
};
Short version:
const add = (a, b) => a + b;
Arrow functions are widely used in modern JavaScript frameworks like React.
Advantages of Functions
1. Reusability
Write code once and use it many times.
2. Better Readability
calculateTax();
generateInvoice();
sendEmail();
The code explains itself.
3. Easier Maintenance
If a bug exists, you only need to fix it in one place.
4. Modularity
Large applications can be broken into smaller, manageable pieces.
5. Easier Testing
Individual functions can be tested independently.
Commonly Used Built-In Functions and Methods
Output
console.log()
Number Conversion
Number()
parseInt()
parseFloat()
String Methods
toUpperCase()
toLowerCase()
trim()
includes()
slice()
replace()
Array Methods
push()
pop()
shift()
unshift()
map()
filter()
reduce()
find()
Math Methods
Math.max()
Math.min()
Math.random()
Math.floor()
Math.ceil()
Math.round()
Timer Functions
setTimeout()
setInterval()
These are frequently used in real-world applications.
References:
https://www.geeksforgeeks.org/javascript/functions-in-javascript/
https://www.w3schools.com/js/js_functions.asp
Top comments (0)