🏠

🛠️ Functions in JavaScript

🌟 Objective: Master JavaScript functions from fundamentals to advanced use cases with real-world examples.

📑 Table of Contents

🔧 What are Functions?

Functions are reusable blocks of code that perform a specific task. They help in breaking programs into smaller, manageable chunks and improve code reusability.

✏️ Function Declaration

function greet(name) {
  console.log("Hello, " + name + "!");
}
greet("Amina"); // Output: Hello, Amina!

📝 Function Expression

A function can also be stored in a variable.

const greet = function(name) {
  return `Hi, ${name}`;
};
console.log(greet("Ali")); // Hi, Ali

➡️ Arrow Functions

Introduced in ES6, arrow functions are a shorter syntax for writing functions.

const square = num => num * num;
console.log(square(4)); // 16

🎯 Parameters vs Arguments

function add(x, y) { // x and y are parameters
  return x + y;
}
add(5, 3); // 5 and 3 are arguments

🔁 Return Statement

The return statement ends function execution and returns a value.

function multiply(a, b) {
  return a * b;
}
let result = multiply(4, 5); // 20

🔧 Default Parameters

ES6 allows you to assign default values to parameters.

function greet(name = "Guest") {
  console.log("Welcome, " + name);
}
greet(); // Welcome, Guest

📦 Rest Parameters

Allows you to handle an indefinite number of arguments as an array.

function sum(...numbers) {
  return numbers.reduce((total, num) => total + num);
}
console.log(sum(1, 2, 3, 4)); // 10

📞 Callback Functions

A callback is a function passed as an argument to another function.

function processUser(name, callback) {
  callback(name);
}
function sayHello(user) {
  console.log("Hello " + user);
}
processUser("Zahra", sayHello); // Hello Zahra

🙈 Anonymous Functions

Functions without a name. Often used in expressions or callbacks.

setTimeout(function() {
  console.log("Hello after 1 second");
}, 1000);

⚡ Immediately Invoked Function Expression (IIFE)

Runs immediately after being defined.

(function() {
  console.log("This runs instantly!");
})();

📤 Function Hoisting

Function declarations are hoisted to the top of their scope.

greet();
function greet() {
  console.log("Hi!");
} // This works!

🌐 Scope and Closures

Block vs Function Scope

function outer() {
  let outerVar = "I'm outside!";

  function inner() {
    console.log(outerVar); // Accesses outer scope
  }

  return inner;
}

const closureFunc = outer();
closureFunc(); // I'm outside!

This is a closure — inner function remembers variables from its parent scope.

🌍 Real-world Examples

Form Validation

function validateEmail(email) {
  return email.includes("@");
}

Discount Calculation

function calculateDiscount(price, percent) {
  return price - (price * percent / 100);
}

Array Filtering

const numbers = [1, 2, 3, 4, 5, 6];
const even = numbers.filter(num => num % 2 === 0);
console.log(even); // [2, 4, 6]