DEV Community

Lokesh
Lokesh

Posted on

JavaScript Functions

What Are Functions?

A function is a reusable block of code designed to perform a particular task.

Instead of writing the same code multiple times, we can write it once inside a function and use it whenever we need it.

For example, if we want to display a welcome message several times, we can create a function for it.

1. Creating and Calling a Function

Let's create a simple function.

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

greet();
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome to JavaScript!
Enter fullscreen mode Exit fullscreen mode

Here:

  • function is used to declare a function.
  • greet is the function name.
  • The code inside { } is the function body.
  • greet() calls the function and executes its code.

Defining a function does not automatically execute it. We need to call it.

2. Functions with Parameters

Parameters allow us to pass information into a function.

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

greet("John");
greet("David");
Enter fullscreen mode Exit fullscreen mode

Output:

Hello John
Hello David
Enter fullscreen mode Exit fullscreen mode

Here, name is a parameter, while "John" and "David" are arguments passed when calling the function.

This allows us to reuse the same function with different values.

3. Functions with Return Values

The return statement sends a result back to the place where the function was called.

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

let result = add(10, 20);

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

Here, the function adds two numbers and returns the result. We store that result in the result variable.

One important point: return sends a value back, while console.log() displays a value in the console.

5. Why Are Functions Important?

Functions help us:

  • Reuse code instead of repeating it.
  • Organize programs into smaller parts.
  • Perform calculations such as totals and averages.
  • Process user input.
  • Make code easier to read and maintain.

For example, in a product management application, we can create separate functions to add products, calculate prices, and apply discounts.

Top comments (0)