C
JavaScript/Functions/Lesson 07

Functions — *Reusable Code Blocks*

45 min·theory
This chapter
1/4

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

javascript
// 1️⃣ Function declaration
function add1(a, b) {
    return a + b;
}

// 2️⃣ Function expression
const add2 = function(a, b) {
    return a + b;
};

// 3️⃣ Arrow function (2015+) — most common
const add3 = (a, b) => a + b;

// 4️⃣ Method (inside an object)
const calculator = {
    add(a, b) { return a + b; }
};

// ▶️ Call all four — results are the same
console.log(add1(2, 3));            // 5
console.log(add2(2, 3));            // 5
console.log(add3(2, 3));            // 5
console.log(calculator.add(2, 3));  // 5

// 💡 Declaring with the same name (`add`) 4 times would cause a SyntaxError → separated as add1·2·3 for learning purposes

Function Declaration vs. Arrow Function — Which One?

Function declaration:

  • Hoisting (can be used before declaration)
  • Has its own this
  • Uses the function keyword

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

javascript
// 1️⃣ Default values — if no argument is given, the value after = is used automatically
const greet = (name = "Anonymous") => `Hi, ${name}`;
console.log(greet());         // "Hi, Anonymous"   ← no argument given, so default value used
console.log(greet("Hong"));     // "Hi, Hong"     ← argument given, so that value used

// 2️⃣ Rest parameters — any number of arguments are bundled into an array
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3, 4));        // 10
console.log(sum(1, 2, 3, 4, 5, 6));  // 21
console.log(sum());                  // 0   ← OK even with no arguments

// 3️⃣ Destructuring — extracts only the necessary properties from an object
const printUser = ({ name, age }) => console.log(`${name} (${age})`);
printUser({ name: "Hong", age: 28 });   // Output: "Hong (28)"

Functions Are Values

javascript
// 1️⃣ Store in a variable — functions are also values, so they can be stored in variables
const fn = () => "hi";
console.log(fn());   // "hi"

// 2️⃣ Pass as an argument — "pass" a function to methods like map
const doubled = [1, 2, 3].map(x => x * 2);
console.log(doubled);   // [2, 4, 6]

// 3️⃣ Return — a function returns a function (closure)
function makeCounter() {
    let count = 0;
    return () => ++count;        // returns a function
}
const counter = makeCounter();
console.log(counter());   // 1
console.log(counter());   // 2
console.log(counter());   // 3   ← count persists and continues to increment

This is the foundation of functional programming. Callbacks, higher-order functions, and closures all build on this.

Pure Functions — Recommended Pattern

javascript
// ✅ Pure: same input → same output + no side effects
const double = (n) => n * 2;
console.log(double(3));   // 6   ← no matter how many times it's called, same input yields same output
console.log(double(3));   // 6

// ❌ Impure: modifies external state (has side effects)
let count = 0;
const increment = () => { count++; };   // touches the external count

increment();
increment();
console.log(count);   // 2   ← external state changes with each call (unpredictable)

Benefits of pure functions:

  • Easy to test — just verify inputs and outputs
  • Predictable
  • Safe for parallel processing
  • Cacheable (memoization)

Common Pitfalls

1. Forgetting return:

javascript
const addBad   = (a, b) => { a + b };       // ❌ no return inside curly braces
const addGood1 = (a, b) => a + b;           // ✅ no curly braces → expression auto-returns
const addGood2 = (a, b) => { return a + b; }; // ✅ curly braces + explicit return

console.log(addBad(2, 3));    // undefined   ← 🙀 because no return!
console.log(addGood1(2, 3));  // 5
console.log(addGood2(2, 3));  // 5

2. this in arrow functions:

javascript
const obj = {
    name: "Hong",
    greet: () => console.log(this.name)   // undefined!
};
// Arrow functions have no own this → use surrounding (global) this

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

Write all 4 function types and run them alongside parameter patterns to compare the results.
✏️ JS 코드
📟 Console output
▶ Press the Run button
⚠️ Runs in a browser sandbox — only console.log() is supported; alert/fetch are not.

🤖 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 this binding 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.

Function Basics - JavaScript