Functions — *Reusable Code Blocks*
Functions — *Reusable Code Blocks*
🎯 After reading this lesson
By the end of this lesson, you will be able to do the following 3 things with confidence.
- ▸✅ Function declaration vs. expression + hoisting differences
- ▸✅ Parameter default values + rest · spread usage
- ▸✅ Defining pure functions / side effects / first-class functions
Keep the learning objectives as a checklist — close the lesson once you can answer all of them.
4 Ways to Write a Function
The Essence of Functions
Function = a reusable block of code that takes input, processes it, and returns a result. In JS, functions are first-class citizens — they can be treated just like variables.
4 Ways to Write a Function
Function Declaration vs. Arrow Function — Which One?
Function declaration:
- ▸Hoisting (can be used before declaration)
- ▸Has its own
this - ▸Uses the
functionkeyword
Arrow function:
- ▸No hoisting (cannot be used before declaration)
- ▸Uses the surrounding
this(the biggest difference) - ▸Shorter syntax
Industry consensus: Use arrow functions in most cases. Use regular functions only for class methods and constructors.
Parameter Patterns
Functions Are Values
This is the foundation of functional programming. Callbacks, higher-order functions, and closures all build on this.
Pure Functions — Recommended Pattern
Benefits of pure functions:
- ▸Easy to test — just verify inputs and outputs
- ▸Predictable
- ▸Safe for parallel processing
- ▸Cacheable (memoization)
Common Pitfalls
1. Forgetting return:
2. this in arrow functions:
Quick Summary
- ▸Arrow functions are the modern standard
- ▸Functions are values — they can be passed, returned, and stored
- ▸Pure functions are the safe pattern
- ▸Make full use of default parameters, rest, and destructuring
⚡ Try It Yourself — 4 Function Types + Defaults · Rest
🤖 Try prompting AI like this
Knowing the concepts from this lesson lets you give AI specific instructions. Instead of a vague 'fix this,' you make vocabulary-driven requests — that is where token savings begin.
- ▸'Convert this function declaration to an arrow function and check for
thisbinding differences' - ▸'Refactor this function into a pure function (remove side effects)'
- ▸'Apply appropriate default parameter values + destructuring to this function'
Why This Reduces Tokens
Without the concepts, you have to ask 'What does that mean?' after every AI response. Those follow-up questions eat your tokens. Learn the concepts once, and the conversation ends in one turn.