Part 1: The Core Concept - What is a Function?

First Thought: A function is a reusable "code machine" or a "recipe."

Imagine you have a task you need to do over and over, like making a sandwich. Instead of re-writing the instructions (get bread, get cheese, etc.) every single time, you write the recipe down once and give it a name, like "Make Turkey Sandwich."

Why do we need them? The DRY Principle: Don't Repeat Yourself. Functions let you write a piece of logic once and reuse it hundreds of times.

A. The Three Core Parts

  1. Declaration (Writing the Recipe): This is where you define the function and give it a name.
  2. Calling (Using the Recipe): This is where you execute the function.
  3. Parameters & Return Value (Ingredients & Finished Dish): How you pass data into a function and get a result out of it.

B. Basic Syntax

// 1. DECLARATION: Writing the recipe
//    - `function` is the keyword.
//    - `greet` is the name of our function.
//    - `(name)` is the parameter, a placeholder for the input.
function greet(name) {
  // The code inside the {} is the "body" of the function.
  const message = `Hello, ${name}!`;
  return message; // 3. RETURN VALUE: Giving back the result.
}

// 2. CALLING: Using the recipe with a specific ingredient ("Alice")
const greetingForAlice = greet("Alice");
console.log(greetingForAlice); // Outputs: "Hello, Alice!"

const greetingForBob = greet("Bob");
console.log(greetingForBob);   // Outputs: "Hello, Bob!"


Part 2: Different Ways to Create Functions

There are three main ways to create functions in JavaScript, and their differences are important.

A. Function Declaration