🧠 JavaScript Function Concepts – Arrow Functions, Return Statements, Parameters & Arguments, and Callback Functions

Payal PorwalPayal Porwal
7 min read

These four concepts are commonly used in React development and modern JavaScript. This article explains each of them step-by-step with 3 real-life examples per topic, using simple English so both beginners and working professionals can learn easily.


βœ… 1. Arrow Functions

πŸ“˜ What is an Arrow Function?

Arrow functions are a shorter way to write functions in JavaScript. They were introduced in ES6 (2015).

πŸ” Syntax:

const functionName = (parameters) => {
  // code
};

πŸ”„ Example 1 – Add two numbers

const add = (a, b) => {
  return a + b;
};

console.log(add(3, 4)); // Output: 7

🧺 Example 2 – Show welcome message

const greet = (name) => {
  console.log(`Welcome, ${name}!`);
};

greet("Payal"); // Output: Welcome, Payal!

πŸ“… Example 3 – Get current date

const getDate = () => new Date();

console.log(getDate()); // Output: Current Date and Time

βœ… If the function has only one line, we can skip curly braces {} and return keyword (see Example 3).


πŸ”‘ Benefits:

  • Shorter syntax

  • Easier to write inline functions

  • Common in React components and event handlers


βœ… 2. Return Statements

πŸ“˜ What is a Return Statement?

The return keyword is used to send output from a function to where it was called.
Once a return is hit, the function stops running.


🍎 Example 1 – Calculate square

function square(num) {
  return num * num;
}

console.log(square(5)); // Output: 25

πŸ’¬ Example 2 – Return a greeting message

function getGreeting(name) {
  return `Hello, ${name}!`;
}

const msg = getGreeting("Amit");
console.log(msg); // Output: Hello, Amit!

🎟️ Example 3 – Check eligibility

function isEligible(age) {
  if (age >= 18) {
    return true;
  }
  return false;
}

console.log(isEligible(20)); // Output: true
console.log(isEligible(16)); // Output: false

πŸ”‘ Notes:

  • A function can return any data type (string, number, array, object, etc.)

  • After return, no code below it is executed.


βœ… 3. Parameters & Arguments

πŸ“˜ What are Parameters and Arguments?

  • Parameters are placeholders used in function definition.

  • Arguments are the actual values passed when the function is called.

function greet(name) { // name = parameter
  console.log(`Hello, ${name}`);
}

greet("Payal"); // "Payal" = argument

πŸ’‘ Example 1 – Add two numbers

function add(a, b) {
  console.log("Sum is:", a + b);
}

add(10, 5); // Output: Sum is: 15

πŸ“¦ Example 2 – Display item with price

function showItem(item, price) {
  console.log(`${item} costs β‚Ή${price}`);
}

showItem("Milk", 45); // Output: Milk costs β‚Ή45

🎫 Example 3 – Calculate area of a rectangle

function calculateArea(length, width) {
  return length * width;
}

console.log(calculateArea(5, 10)); // Output: 50

πŸ”‘ Notes:

  • You can pass multiple arguments separated by commas.

  • If no argument is passed, the parameter will be undefined.


βœ… 4. Callback Functions

πŸ“˜ What is a Callback Function?

A callback function is a function passed as an argument to another function.

It runs after some task is completed.

Used a lot in:

  • Events

  • API calls

  • Array methods (like map, forEach)

  • Asynchronous code (React, Node.js)


⏱️ Example 1 – Basic callback function

function greet(name, callback) {
  console.log("Hi", name);
  callback();
}

function sayBye() {
  console.log("Bye!");
}

greet("Payal", sayBye);

// Output:
// Hi Payal
// Bye!

πŸ›’ Example 2 – After adding item to cart, show success

function addToCart(item, callback) {
  console.log(`${item} added to cart.`);
  callback();
}

addToCart("Shampoo", () => {
  console.log("Cart updated successfully!");
});

🧹 Example 3 – Run after cleaning

function cleanRoom(done) {
  console.log("Cleaning the room...");
  done(); // callback
}

cleanRoom(function() {
  console.log("Room is clean now!");
});

πŸ”‘ Benefits of Callbacks:

  • Write reusable, modular code

  • Helps in asynchronous operations

  • Backbone of many JS frameworks like React, Node.js


🧠 Final Recap Table

ConceptDescriptionReal-world Use
Arrow FunctionShort, modern way to write functionsReact components, event handlers
Return StatementSends output from functionProcessing values (math, strings, logic)
Parameters/ArgumentsPass dynamic data to functionsUser input, product data, API calls
Callback FunctionFunction inside function, run after main task doneAsync tasks, UI updates, event listeners

Great! Here's a mini project that uses all 4 JavaScript function concepts:


πŸ§ͺ Mini Project: Smart To-Do List Manager

Concepts Covered:
βœ… Arrow Functions
βœ… Return Statements
βœ… Parameters & Arguments
βœ… Callback Functions


🧠 Project Goal:

We will build a small To-Do List App where:

  • Users can add tasks.

  • Each task will have a priority level (High, Medium, Low).

  • Tasks will display dynamically.

  • On completing a task, a message will show using a callback function.

  • We’ll use arrow functions, parameters, return values, and callbacks together.


πŸ“ File Structure

  • index.html – UI structure

  • style.css – Basic styling

  • script.js – Full logic with function concepts


πŸ“„ index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Smart To-Do List</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <div class="container">
    <h2>πŸ“ Smart To-Do List</h2>
    <input type="text" id="taskInput" placeholder="Enter your task..." />
    <select id="priorityInput">
      <option value="High">High</option>
      <option value="Medium">Medium</option>
      <option value="Low">Low</option>
    </select>
    <button onclick="handleAddTask()">Add Task</button>

    <ul id="taskList"></ul>
  </div>

  <script src="script.js"></script>
</body>
</html>

🎨 style.css

body {
  font-family: sans-serif;
  background: #f2f2f2;
  display: flex;
  justify-content: center;
  margin-top: 50px;
}

.container {
  background: white;
  padding: 25px;
  border-radius: 10px;
  width: 350px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

input, select, button {
  width: 100%;
  margin: 10px 0;
  padding: 8px;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  background: #e6f7ff;
  margin: 5px 0;
  padding: 10px;
  border-radius: 5px;
  position: relative;
}

button.complete-btn {
  position: absolute;
  right: 10px;
  top: 10px;
  padding: 2px 6px;
  font-size: 12px;
  cursor: pointer;
}

πŸ“œ script.js

// βœ… Arrow Function to create a task object with return statement
const createTask = (name, priority) => {
  return {
    name,
    priority,
    createdAt: new Date().toLocaleString()
  };
};

// βœ… Function using parameters & return value
function generateTaskHTML(taskObj) {
  return `<strong>${taskObj.name}</strong> 
  <br>Priority: ${taskObj.priority}
  <br><small>Added on: ${taskObj.createdAt}</small>`;
}

// βœ… Callback function example
function showCompletionMessage(taskName, callback) {
  console.log(`βœ… "${taskName}" marked as completed.`);
  callback(); // trigger any post-completion logic
}

// βœ… Arrow Function to handle task addition
const handleAddTask = () => {
  const taskInput = document.getElementById("taskInput").value.trim();
  const priorityInput = document.getElementById("priorityInput").value;

  if (!taskInput) {
    alert("Please enter a task.");
    return;
  }

  // create task object
  const task = createTask(taskInput, priorityInput);

  // create and add to DOM
  const listItem = document.createElement("li");
  listItem.innerHTML = generateTaskHTML(task);

  const completeBtn = document.createElement("button");
  completeBtn.textContent = "βœ”";
  completeBtn.className = "complete-btn";

  // βœ… Callback Function used on click
  completeBtn.addEventListener("click", () => {
    showCompletionMessage(task.name, () => {
      listItem.remove();
      alert(`"${task.name}" has been removed from the list.`);
    });
  });

  listItem.appendChild(completeBtn);
  document.getElementById("taskList").appendChild(listItem);

  // clear inputs
  document.getElementById("taskInput").value = "";
};

πŸ§‘β€πŸ« Explanation of Concepts Used

ConceptUsed InExplanation
Arrow FunctioncreateTask, handleAddTaskShort and clean function writing
Return StatementcreateTask, generateTaskHTMLReturns object & formatted string
Parameters/ArgsAll functions like createTask(name, priority)Pass user inputs dynamically
Callback FunctionshowCompletionMessage(taskName, callback)Run code after task is completed

πŸ’‘ Real-life Utility

  • Used in React projects for managing task lists, reminders

  • Uses pure JS logic, perfect before introducing useState or components


βœ… Bonus Suggestions (Practice Ideas)

Let students:

  • Add a "Mark as Important" feature with icons

  • Add filters (e.g., show only high priority tasks)

  • Replace alerts with custom styled popups


πŸ”š Conclusion

This mini project is a complete hands-on exercise that helps students understand how modern JavaScript functions are used in daily projects β€” including React-style logic, callbacks, and clean arrow functions.


πŸš€ What's Next?

Next in the series, we will learn:

  • Higher Order Functions

  • Closures

  • Rest & Default Parameters

  • IIFE


πŸ”” Stay Connected

If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Javascript notes, tutorials, and project ideas β€” πŸ“© Subscribe to our newsletter by entering your email below.

And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, πŸŽ₯ Don’t forget to subscribe to my YouTube channel – Knowledge Factory 22 – for regular content on tech concepts, career tips, and coding insights!

Stay curious. Keep building. πŸš€

0
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: πŸš€ In-depth explorations of emerging technologies πŸ’‘ Practical tutorials and how-to guides πŸ”§Insights on software development best practices πŸš€Reviews of the latest tools and frameworks πŸ’‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟