DEV Community

Cover image for JavaScript Functions Explained
Saravanan Lakshmanan
Saravanan Lakshmanan

Posted on

JavaScript Functions Explained

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;
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

This quickly becomes difficult to maintain.

With a function:

function welcome() {
    console.log("Welcome");
}

welcome();
welcome();
welcome();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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() {}
Enter fullscreen mode Exit fullscreen mode

Poor Examples

function a() {}
function xyz() {}
function temp() {}
Enter fullscreen mode Exit fullscreen mode

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() {}
Enter fullscreen mode Exit fullscreen mode

Invalid Names

function 123add() {}
function my-name() {}
function function() {}
Enter fullscreen mode Exit fullscreen mode

Anatomy of a Function

function add(a, b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Function Keyword:

function
Enter fullscreen mode Exit fullscreen mode

Tells JavaScript you're creating a function.

Function Name:

add
Enter fullscreen mode Exit fullscreen mode

Used to call the function.

Parameters:

(a, b)
Enter fullscreen mode Exit fullscreen mode

Inputs accepted by the function.

Function Body:

{
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Contains the logic that gets executed.


Calling a Function

Creating a function does not execute it.

function greet() {
    console.log("Hello");
}
Enter fullscreen mode Exit fullscreen mode

Nothing happens until you call it:

greet();
Enter fullscreen mode Exit fullscreen mode

Output:

Hello
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Here a and b are parameters.

Arguments

Actual values passed when calling the function.

add(10, 20);
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Internally, JavaScript treats it like:

let result = 30;
Enter fullscreen mode Exit fullscreen mode

because:

add(10, 20)
Enter fullscreen mode Exit fullscreen mode

returns:

30
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Purpose:

Display information in the console.

Output:

30
Enter fullscreen mode Exit fullscreen mode

However, the value cannot easily be reused.

return

function add(a, b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output:

60
Enter fullscreen mode Exit fullscreen mode

This flexibility is why professional developers use return extensively.


Function Declaration

Traditional way of creating functions.

function add(a, b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Function Expression

A function stored in a variable.

const add = function(a, b) {
    return a + b;
};
Enter fullscreen mode Exit fullscreen mode

Arrow Function

Modern syntax introduced in ES6.

const add = (a, b) => {
    return a + b;
};
Enter fullscreen mode Exit fullscreen mode

Short version:

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Number Conversion

Number()
parseInt()
parseFloat()
Enter fullscreen mode Exit fullscreen mode

String Methods

toUpperCase()
toLowerCase()
trim()
includes()
slice()
replace()
Enter fullscreen mode Exit fullscreen mode

Array Methods

push()
pop()
shift()
unshift()
map()
filter()
reduce()
find()
Enter fullscreen mode Exit fullscreen mode

Math Methods

Math.max()
Math.min()
Math.random()
Math.floor()
Math.ceil()
Math.round()
Enter fullscreen mode Exit fullscreen mode

Timer Functions

setTimeout()
setInterval()
Enter fullscreen mode Exit fullscreen mode

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)