🔧 Introduction to Functions in JavaScript

Functions in JavaScript are blocks of reusable code that perform a specific task. Instead of writing the same code multiple times, we can create a function and call it wherever needed.


📘 What is a Function?

A function is a self-contained block of code that can be executed when it is called or invoked.

✅ Syntax of a Function

function functionName(parameters) {
  // code to be executed
}

🧪 Example:

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

greetUser("Rahul"); // Output: Hello, Rahul!

🧱 Types of Functions in JavaScript

1. 👉 User-defined Functions

Functions created by the user to perform specific tasks.

function add(a, b) {
  return a + b;
}
console.log(add(5, 3)); // Output: 8

2. 👉 Built-in Functions

JavaScript provides many pre-defined functions like:

  • parseInt()
  • alert()
  • prompt()
  • Math.round()

3. 👉 Anonymous Functions

Functions without a name, usually assigned to a variable.

let show = function() {
  console.log("Anonymous Function");
};
show();

4. 👉 Arrow Functions (ES6)

Shorter syntax for writing functions.

const multiply = (x, y) => x * y;
console.log(multiply(4, 5)); // Output: 20

🔄 Function Parameters and Arguments

  • Parameters: Names listed in the function definition.
  • Arguments: Actual values passed to the function.
function subtract(x, y) {
  return x - y;
}
console.log(subtract(10, 4)); // 6

🔙 Return Statement

Functions can return values using the return keyword.

function square(n) {
  return n * n;
}
console.log(square(6)); // Output: 36

📋 Advantages of Using Functions

  • ✅ Code reusability
  • ✅ Better code organization
  • ✅ Easier debugging and maintenance
  • ✅ Improves program readability

📌 Summary

  • Functions are reusable blocks of code in JavaScript.
  • They can accept inputs (parameters) and return outputs.
  • Arrow functions and anonymous functions offer advanced ways to define functions.
  • Using functions helps in writing cleaner and more efficient code. 🧠💻