JavaScript Functions: Complete Guide
Master JavaScript functions. Learn function declarations, expressions, arrow functions, parameters, and scope.
JavaScript Functions
What's a Function?
A function is like a recipe. You write the steps once, then use it whenever you need to make that dish.
Think of it like this:
``` ┌─────────────────────┐ │ Function Recipe │ │ │ │ Input: Ingredients │ │ Steps: What to do │ │ Output: Result │ └─────────────────────┘ ```
Instead of writing the same code over and over, you write it once in a function, then call that function whenever you need it.
Why Use Functions?
Let's say you need to calculate the area of a square three times:
**Without a function:** ```javascript const area1 = 5 * 5; const area2 = 10 * 10; const area3 = 15 * 15; ```
**With a function:** ```javascript function calculateArea(side) { return side * side; }
const area1 = calculateArea(5); const area2 = calculateArea(10); const area3 = calculateArea(15); ```
The function version is shorter, clearer, and if you need to change how area is calculated, you only change it in one place.
Your First Function
Let's create a simple function step by step:
**Step 1:** Write the word `function` ```javascript function ```
**Step 2:** Give it a name ```javascript function greet ```
**Step 3:** Add parentheses (this is where inputs go) ```javascript function greet() ```
**Step 4:** Add curly braces (this is where the code goes) ```javascript function greet() { } ```
**Step 5:** Write what it should do ```javascript function greet() { console.log('Hello!'); } ```
**Step 6:** Call it (use it) ```javascript greet(); // Shows: Hello! ```
Functions with Inputs (Parameters)
Functions can take inputs. Like a vending machine - you put money in, you get a snack out.
```javascript function greet(name) { console.log('Hello, ' + name + '!'); }
greet('John'); // Shows: Hello, John! greet('Sarah'); // Shows: Hello, Sarah! ```
The `name` inside the parentheses is a parameter. It's like a variable that gets its value when you call the function.
Functions That Give Back Results (Return)
Functions can also give you something back:
```javascript function add(a, b) { return a + b; }
const result = add(5, 3); console.log(result); // Shows: 8 ```
The `return` keyword sends the result back. Without it, the function doesn't give you anything back.
Arrow Functions (Shorter Way)
There's a shorter way to write functions:
```javascript const greet = (name) => { return 'Hello, ' + name + '!'; }; ```
This does the same thing as a regular function, just shorter. You'll see this style a lot in modern JavaScript.
Real Example: A Useful Function
Let's say you're building a website and need to format prices:
```javascript function formatPrice(amount) { return '$' + amount.toFixed(2); }
const price1 = formatPrice(19.9); // "$19.90" const price2 = formatPrice(5); // "$5.00" const price3 = formatPrice(99.999); // "$100.00" ```
Now you can format any price the same way, just by calling the function.
How Functions Work - Step by Step
When you write:
```javascript function multiply(a, b) { return a * b; }
const result = multiply(4, 5); ```
Here's what happens:
``` 1. Function is defined ┌─────────────────────┐ │ function multiply() │ │ { return a * b; } │ └─────────────────────┘
2. Function is called multiply(4, 5) 3. Values are passed in a = 4, b = 5 4. Code inside runs 4 * 5 = 20 5. Result is returned result = 20 ```
Quick Tips
1. **Give functions clear names** - `calculateTotal` is better than `calc` or `x` 2. **Keep functions focused** - One function should do one thing 3. **Use return when you need a result** - Otherwise the function just runs code
Functions are one of the most important concepts in programming. Once you understand them, you can build much more complex programs.