DEV Community

ASHWINTH
ASHWINTH

Posted on

Js-Functions

What is javascript functions?

A function is a reusable block of code that runs when we call it.

Example
function greet() {
    console.log("Hello, Welcome!");
}

greet();
Enter fullscreen mode Exit fullscreen mode

Here, greet() is a function. When we call greet(), the code inside the function is executed.

Function with Parameters

Functions can accept values called parameters. Parameters allow us to pass different values to a function.

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

greet("Aswin");

Output:

Hello Aswin
Enter fullscreen mode Exit fullscreen mode

In this example, name is the parameter and "Aswin" is the value passed to the function.

Function with Return Value

A function can also return a value using the return keyword.

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

let result = add(10, 20);

console.log(result);

Output:

30
Enter fullscreen mode Exit fullscreen mode

The function calculates the sum and returns the result.

Why Do We Use Functions?

Functions help us to:

Reuse code
Reduce duplicate code
Keep programs organized
Make code easier to understand
Make debugging easier

Conclusion

JavaScript functions make our code simple, reusable, and organized. Once you understand how to create, call, pass parameters, and return values from functions, you can write JavaScript programs more efficiently.

Top comments (0)