Functions in JavaScript

📍 What are Functions?

In JavaScript, a function is a reusable block of code designed to perform a particular task. Functions help you break programs into smaller, manageable pieces and avoid repeating code. 🔁

>>“Write once, use many times — that’s the power of functions!” 🔂

🔤 Syntax

Function Declaration Syntax

function functionName(parameters) {
  // code to execute
}

- functionName is the identifier you give your function.
- parameters are inputs passed into the function.
- The code inside the runs when the function is called.

🧪 Example

Simple Greeting Function

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

greet("Alice"); // Hello, Alice!

🔁 Why Use Functions?

  • ✨ Code reusability
  • 🧠 Logical organization of tasks
  • 📦 Helps in debugging and testing
  • 📐 Can be composed to build more complex features

🧩 Function Declaration vs Expression

Function Declaration:

Function Declaration

function add(x, y) {
  return x + y;
}

Function Expression:

Function Expression

const add = function(x, y) {
  return x + y;
};

Note

💡 Function declarations are hoisted, meaning they can be called before they're defined. Function expressions are not.

⚡ Arrow Functions

Arrow Function Syntax

const multiply = (a, b) => a * b;

console.log(multiply(3, 4)); // 12

Arrow functions provide a shorter syntax and behave differently with this. They're commonly used in modern JavaScript. 🏹

📦 Default Parameters

Function with Default Parameter

function greet(name = "Stranger") {
  console.log("Hello, " + name + "!");
}

greet(); // Hello, Stranger!

♻️ Return Values

Returning from a Function

function square(num) {
  return num * num;
}

let result = square(5); // 25

Note

💡 The return statement sends a value back to where the function was called.

📚 Higher-Order Functions

Functions that accept other functions as arguments or return a function are called higher-order functions. They are the backbone of functional programming in JavaScript.

Higher-Order Example

function repeatTwice(fn) {
  fn();
  fn();
}

repeatTwice(() => console.log("Hi!"));

✅ Summary

  • Functions group reusable logic into callable blocks 🧱
  • Use function keyword, or arrow functions for concise syntax 🏹
  • Functions can accept parameters and return results 🔁
  • Used in callbacks, loops, events, and more 💥

📚 Resources

>>“A function is like a magic box — give it input, get desired output.” 🎁