What Are JavaScript Functions? See Examples

Functions are one of the most important concepts in JavaScript. They allow you to group code into reusable blocks that can be called whenever needed. Functions make your code modular, organized, and easier to maintain.

In this blog, we’ll explain different types of functions with examples.


What Is a Function?

A function is a block of code designed to perform a particular task. It can take inputs, called parameters, and return an output using the return statement.

Basic Example

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

console.log(greet("Sagar")); // Hello, Sagar!

1. Function Declaration

Also called named functions, declared using the function keyword.

Example

function add(a, b) {
  return a + b;
}
console.log(add(5, 10)); // 15

2. Function Expression

Functions can also be stored in a variable.

Example

const multiply = function(x, y) {
  return x * y;
};
console.log(multiply(5, 4)); // 20

3. Arrow Functions (ES6)

Arrow functions provide a shorter syntax.

Example

const square = n => n * n;
console.log(square(5)); // 25

4. Anonymous Functions

Functions without a name, often used as callbacks.

Example

setTimeout(function() {
  console.log("This runs after 2 seconds");
}, 2000);

5. Parameters and Arguments

  • Parameters are placeholders in function definition.
  • Arguments are values passed when calling the function.

Example

function greet(firstName, lastName) {
  return `Hello, ${firstName} ${lastName}!`;
}

console.log(greet("Sagar", "Sidana")); // Hello, Sagar Sidana!

6. Return Statement

Functions can return a value using return. If no return is specified, it returns undefined.

Example

function add(a, b) {
  return a + b;
}
let sum = add(10, 20);
console.log(sum); // 30

7. Immediately Invoked Function Expression (IIFE)

Functions that run immediately after creation.

Example

(function() {
  console.log("IIFE runs automatically!");
})();

Why Functions Are Important

  • Reusable code blocks
  • Improve readability and structure
  • Reduce redundancy
  • Handle events and callbacks
  • Form the foundation of object-oriented and functional programming

Conclusion

Functions are the backbone of JavaScript programming. Learning how to declare, call, and use functions efficiently is essential for building both simple scripts and complex applications.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *