๐Ÿ”ง 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. ๐Ÿง ๐Ÿ’ป