Functions| Dataplexa

Functions

In real life, we often reuse the same steps again and again. For example, calculating a bill, sending a message, or validating a form.

In JavaScript, functions help us group reusable code so we don’t repeat ourselves.


What Is a Function?

A function is a block of code designed to perform a specific task. You can run the function whenever you need it.

Functions make code cleaner, reusable, and easier to maintain.


Creating a Function

We create a function using the function keyword.


function greet() {
  console.log("Welcome to Dataplexa");
}
  

This function prints a welcome message whenever it is called.


Calling a Function

Creating a function does not run it automatically. You must call the function to execute it.


greet();
  

Every time you call the function, the same code runs.


Functions with Parameters

Parameters allow functions to accept values and work dynamically.


function greetUser(name) {
  console.log("Hello " + name);
}

greetUser("Alex");
greetUser("Sam");
  

Here, the function behaves differently based on the input provided.


Functions with Return Values

Functions can return a value using the return keyword.


function add(a, b) {
  return a + b;
}

let result = add(5, 3);
  

Returned values can be stored or used in other calculations.


Real-World Example

Imagine calculating the total price of items in a cart:


function calculateTotal(price, quantity) {
  return price * quantity;
}

let total = calculateTotal(100, 2);
  

Functions help avoid repeating the same logic throughout the application.


Common Beginner Mistakes

  • Forgetting to call the function
  • Not returning a value when needed
  • Using unclear function names

Always give functions meaningful names that describe their purpose.


Thumb Rules

  • One function should do one job
  • Use clear and descriptive function names
  • Avoid repeating code — use functions
  • Return values when results are needed

More on Functions Later

In this lesson, we focused on basic function creation and usage.

More advanced function concepts are covered in upcoming lessons.


What Comes Next?

Now that you know how to organize code using functions, the next step is understanding where variables and functions live.

In the next lesson, we will learn about scope.