Functions allow you to wrap a piece of code, give it a name, and run it whenever you want. This makes your code reusable and organized.
1. Function Declaration
The traditional way to define a function using the function keyword.
Parameters: The "inputs" you define (like
name).Arguments: The actual values you pass in when calling it (like
"Gemini").Return: The "output" or result of the function.
2. Arrow Functions (ES6+)
A shorter, modern way to write functions. They are very popular in React and modern JavaScript.
3. Scope (Global vs. Local)
Global Scope: Variables defined outside functions; everyone can see them.
Local/Block Scope: Variables defined inside a function or
{}are "private" to that block.
The Code Example
// 1. Function Declaration (The Classic)
function makeJuice(fruit) {
return `Here is your ${fruit} juice! 🥤`;
}
// "Calling" the function
const order1 = makeJuice("Apple");
console.log(order1);
// 2. Arrow Function (The Modern Way)
const addNumbers = (a, b) => {
return a + b;
};
// Shorthand if it's just one line:
const multiply = (a, b) => a * b;
console.log(multiply(5, 4)); // Output: 20
// 3. Understanding Scope
let globalMsg = "I am everywhere"; // Global
function testScope() {
let localMsg = "I am hidden"; // Local
console.log(globalMsg); // Works
console.log(localMsg); // Works
}
testScope();
// console.log(localMsg); // ERROR: localMsg is not defined here!