Functions
35 minFunctions are the fundamental building blocks of JavaScript applications. They allow you to encapsulate code for reuse, organization, and modularity. A function is essentially a set of statements that performs a task or calculates a value.
There are multiple ways to define functions: Function Declarations (hoisted), Function Expressions (not hoisted), and Arrow Functions (ES6, lexically scoped `this`). Understanding the differences is key to mastering scope and context.
Functions in JavaScript are 'First-Class Citizens', meaning they can be assigned to variables, passed as arguments to other functions (callbacks), and returned from other functions (higher-order functions). This enables powerful functional programming patterns.
Parameters act as placeholders for values passed into the function. ES6 introduced Default Parameters (`param = value`) and Rest Parameters (`...args`), making function definitions more flexible and robust.
Key Concepts
- Function Declaration vs. Expression.
- Arrow Functions and lexical `this`.
- First-Class Functions (Callbacks/Higher-Order).
- Parameters vs. Arguments.
- Return values and `void` functions.
Learning Objectives
Master
- Writing functions in all 3 styles
- Understanding hoisting differences
- Using default and rest parameters
- Implementing callbacks effectively
Develop
- Functional thinking
- Code reuse strategies
- Understanding execution context
Tips
- Use Arrow Functions for callbacks to preserve the `this` context.
- Keep functions small and focused on a single task (Single Responsibility Principle).
- Name functions using verbs (e.g., `calculateTotal`, `fetchUser`).
- Use default parameters to handle missing arguments gracefully.
Common Pitfalls
- Confusing `return` (exits function) with `console.log` (prints to screen).
- Forgetting that Function Expressions are not hoisted (must define before use).
- Using Arrow Functions as object methods (they don't have their own `this`).
- Modifying external state (side effects) instead of returning new values.
Summary
- Functions encapsulate reusable logic.
- They are first-class objects in JS.
- Arrow functions offer concise syntax.
- Parameters make functions flexible.
Exercise
Write a function that takes two numbers as arguments and returns their sum.
function add(a, b) {
return a + b;
}
console.log(add(5, 3));
Exercise Tips
- Try rewriting this as an arrow function for comparison.
- Add default parameters to handle cases where arguments might be undefined.
- Add input validation to ensure both arguments are numbers.
- Test with different number types (integers, floats, negative numbers).