DEV Community

Athithya Sivasankarar
Athithya Sivasankarar

Posted on

Understanding Functions in JavaScript

What is a Function?

A function is a block of code designed to perform a specific task.
Instead of writing the same code again and again, you can write it once inside a function and reuse it whenever needed.

Why Use Functions?

Functions are useful because they:

Reduce code repetition
Make code easier to understand
Help in organizing large programs
Allow reuse of logic

How to Create a Function

In JavaScript, you can create a function using the function keyword.

Example:
function greet() {
console.log("Hello, welcome to JavaScript!");
}

How to Call a Function

To execute (run) a function, you simply call it by its name.

greet();

Output:
Hello, welcome to JavaScript!

Functions with Parameters

Functions can take inputs called parameters.

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

Output:
Hello Athithya

Functions with Return Value

A function can return a value using the return keyword.

Example:
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result);

Output:
8

Reference:

[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions]

Top comments (0)