Functions
Reusable Code Blocks
Functions are reusable, named blocks of code that perform a task. They are the fundamental building blocks of JavaScript programs - enabling code reuse, abstraction, and clean organization.
A function is like a vending machine. You put in inputs (parameters), it runs its logic inside, and returns output. You can use the same machine countless times with different inputs.
🔑 Key Concepts
Classic syntax - hoisted, so can be called before defined. function name(params) { return value; }
Concise ES6 syntax: const fn = (params) => expression. Great for callbacks.
Parameters are inputs, return sends output. Default params, rest params (...args), destructuring all work.
💻 Code Examples
⚠️ Common Mistakes
Forgetting return - function silently gives undefined
If you need output, always use the return keyword. A function without return gives undefined.
Writing greet instead of greet() to call it
greet is just a reference to the function. greet() with parentheses actually CALLS it.
Arrow functions and "this" in object methods
Arrow functions inherit "this" from outer scope. Use regular functions for object methods needing "this".
📋 Quick Reference
Live Code Playground
Edit the code and press ▶ Run to see output instantly.