Code Organization

JavaScript Functions

Functions are reusable blocks of code that perform specific tasks. Learn declarations, expressions, arrow functions, scope, and advanced patterns to organize your code effectively.

How do functions work in JavaScript?

A function is a reusable block of code that takes inputs (parameters) and can return a value. Declare one with function add(a, b) { return a + b; } or as an arrow function, const add = (a, b) => a + b;, then call it with add(2, 3). Functions are values: you can store them in variables, pass them to other functions and return them.

function greet(name = "friend") {      // default parameter
  return `Hello, ${name}!`;
}
greet("Ada");                           // "Hello, Ada!"

const square = (n) => n * n;            // arrow function
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);  // rest parameter

What are Functions?

Functions are reusable blocks of code that perform specific tasks. Think of them as mini-programs within your program. Just like mathematical functions, they can take inputs (parameters), process them, and return outputs.

Why Use Functions?

  • • Reusability: Write once, use many times
  • • Organization: Break complex problems into smaller parts
  • • Maintainability: Update code in one place
  • • Testing: Test individual pieces of functionality
  • • Abstraction: Hide complex implementation details

Real-World Analogy

Think of a coffee machine:

  • • Input: Coffee beans, water
  • • Process: Grind, brew, heat
  • • Output: Hot coffee
  • • Reusable: Same process every time

Function Anatomy

function functionName(parameters) {
  // Function body
  return result;
}
function: Keyword
functionName: Identifier
parameters: Inputs
result: Output

Function Types & Syntax

JavaScript offers multiple ways to create functions, each with its own syntax and use cases. Understanding the differences helps you choose the right approach for different situations.

Function Declaration

function greet(name) {
  return "Hello, " + name;
}

Characteristics:

  • • Hoisted (can call before declaration)
  • • Has function name
  • • Traditional syntax
  • • Can be called anywhere in scope

Function Expression

const greet = function(name) {
  return "Hello, " + name;
};

Characteristics:

  • • Not hoisted
  • • Can be anonymous
  • • Assigned to variable
  • • Call after assignment only

Arrow Function (ES6)

const greet = (name) => {
  return "Hello, " + name;
};

Characteristics:

  • • Shorter syntax
  • • Lexical this binding
  • • Implicit return (single expression)
  • • Modern ES6+ feature

When to Use Which

Declaration: Main functions, utilities
Expression: Conditional creation, callbacks
Arrow: Short functions, array methods

Parameters & Return Values

Function Parameters

Basic Parameters

function add(a, b) {
  return a + b;
}

Default Parameters

function greet(name = "World") {
  return "Hello, " + name;
}

Rest Parameters

function sum(...numbers) {
  return numbers.reduce((a, b) => a + b);
}

Return Values

Simple Return

function multiply(a, b) {
  return a * b;
}

Multiple Returns

function divide(a, b) {
  if (b === 0) return "Error";
  return a / b;
}

Object Return

function createUser(name, age) {
  return { name, age };
}

Parameter Best Practices

Use descriptive parameter names
Provide default values when appropriate
Limit parameters (max 3-4 recommended)
Use objects for multiple parameters

Interactive Functions Demo

Code Editor

<pre id="out"></pre>

Preview

What This Demo Shows:

  • • Function declarations and expressions
  • • Arrow functions with different syntaxes
  • • Higher-order functions and closures
  • • Scope and parameter handling
  • • Practical function patterns

Scope & Closures

Scope determines where variables can be accessed in your code. Closures allow inner functions to access variables from their outer scope, even after the outer function has finished executing.

Global Scope

let globalVar = "I'm global";

function test() {
  console.log(globalVar); // ✅ Accessible
}

console.log(globalVar); // ✅ Accessible

Variables declared outside functions are globally accessible.

Function Scope

function test() {
  let localVar = "I'm local";
  console.log(localVar); // ✅ Accessible
}

console.log(localVar); // ❌ Error!

Variables inside functions are only accessible within that function.

Block Scope (let/const)

if (true) {
  let blockVar = "Block scoped";
  const alsoBlock = "Also block";
}

console.log(blockVar); // ❌ Error!

let and const are block-scoped (within {}).

Closures in Action

function createCounter() {
  let count = 0;
  return function() {
    return ++count;
  };
}

const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2

Inner function remembers outer function's variables.

Practical Closure Examples

Data Privacy

function createAccount(initialBalance) {
  let balance = initialBalance;
  return {
    deposit: (amount) => balance += amount,
    getBalance: () => balance
  };
}

Function Factories

function createMultiplier(factor) {
  return function(number) {
    return number * factor;
  };
}

const double = createMultiplier(2);

Advanced Function Concepts

Higher-Order Functions

Functions that take other functions as arguments or return functions.

// Array methods are higher-order functions
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(x => x * 2);
const evens = numbers.filter(x => x % 2 === 0);
const sum = numbers.reduce((a, b) => a + b, 0);
• map(): Transform each element
• filter(): Select elements that match
• reduce(): Combine all elements

Function Methods

Every function has built-in methods to control how it's called.

function greet(greeting, name) {
  return `${greeting}, ${name}!`;
}

// call() - invoke with specific arguments
greet.call(null, "Hello", "Alice");

// apply() - invoke with array of arguments
greet.apply(null, ["Hi", "Bob"]);

// bind() - create new function with preset args
const sayHello = greet.bind(null, "Hello");

Recursive Functions

Functions that call themselves to solve problems by breaking them into smaller parts.

// Calculate factorial: 5! = 5 × 4 × 3 × 2 × 1
function factorial(n) {
  // Base case - stop recursion
  if (n <= 1) return 1;
  
  // Recursive case
  return n * factorial(n - 1);
}

console.log(factorial(5)); // 120
Key Points: Always include a base case to stop recursion, or you'll get a stack overflow!

Pure Functions

Functions that always return the same output for the same input and have no side effects.

// ✅ Pure function
const add = (a, b) => a + b;

// ❌ Impure - depends on external variable
let total = 0;
const addToTotal = (x) => total += x;

// ❌ Impure - has side effect
const logAndAdd = (a, b) => {
  console.log("Adding numbers");
  return a + b;
};
• Benefits: Predictable, testable, cacheable
• Use when: Calculations, transformations

Common Function Patterns

Validation Functions

const isValidEmail = (email) => {
  const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
  return emailRegex.test(email);
};

const isValidPassword = (password) => {
  return password.length >= 8 &&
         /[A-Z]/.test(password) &&
         /[0-9]/.test(password);
};

console.log(isValidEmail("user@example.com")); // true
console.log(isValidPassword("MyPass123")); // true

Utility Functions

const utils = {
  capitalize: (str) =>
    str.charAt(0).toUpperCase() + str.slice(1),

  formatPrice: (price) =>
    `$${price.toFixed(2)`,

  randomBetween: (min, max) =>
    Math.floor(Math.random() * (max - min + 1)) + min,

  debounce: (func, delay) => {
    let timeoutId;
    return (...args) => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => func(...args), delay);
    };
  }
};

Event Handler Patterns

// Simple event handler
const handleClick = (event) => {
  console.log("Button clicked!", event.target);
};

// Event handler with data
const createClickHandler = (data) => {
  return (event) => {
    console.log("Clicked with data:", data);
  };
};

// Usage
const handler1 = createClickHandler("item-1");
const handler2 = createClickHandler("item-2");

Async Function Patterns

// Promise-based function
const fetchUserData = (userId) => {
  return fetch(`/api/users/${userId}`)
    .then(response => response.json())
    .catch(error => {
      console.error("Failed to fetch user:", error);
      return null;
    });
};

// Async/await version
const fetchUserDataAsync = async (userId) => {
  try {
    const response = await fetch(`/api/users/${userId}`);;
    return await response.json();
  } catch (error) {
    console.error("Failed to fetch user:", error);
    return null;
  }
};

Function Best Practices

Do's

  • • Use descriptive names: calculateTax() not calc()
  • • Keep functions small: One responsibility per function
  • • Use pure functions: Same input → same output
  • • Handle edge cases: Check for null, undefined, empty
  • • Use default parameters: function greet(name = "World")
  • • Return early: Avoid deep nesting with early returns
  • • Comment complex logic: Explain the "why", not the "what"

Function Naming Conventions

Actions: calculateTotal(), processOrder()
Predicates: isValid(), hasPermission()
Getters: getUserName(), getCurrentDate()
Setters: setUserName(), updateStatus()
Handlers: handleClick(), onSubmit()
Creators: createUser(), generateId()

Don'ts

  • • Don't make functions too long: > 20 lines is often too much
  • • Don't use global variables: Pass data through parameters
  • • Don't modify parameters: Treat inputs as read-only
  • • Don't use too many parameters: Consider using objects
  • • Don't nest functions deeply: Extract complex logic
  • • Don't ignore return values: Always handle function results
  • • Don't use abbreviations: calc() → calculate()

Performance Tips

Avoid creating functions in loops: Define outside, call inside
Use arrow functions for callbacks: More efficient this binding
Cache expensive calculations: Store results to avoid recalculation
Use function declarations for hoisting: Available throughout scope
Consider memoization: Cache function results for repeated calls

Code Example: Good vs Bad

❌ Bad Example

function calc(a, b, c) {
  let x = a + b;
  if (c === 1) {
    x = x * 2;
    if (x > 100) {
      x = x - 50;
    }
  } else {
    x = x / 2;
  }
  return x;
}

✅ Good Example

function calculateAdjustedSum(value1, value2, shouldDouble = false) {
  const sum = value1 + value2;
  
  if (shouldDouble) {
    return applyDoubleAndCap(sum);
  }
  
  return sum / 2;
}

function applyDoubleAndCap(value) {
  const doubled = value * 2;
  return doubled > 100 ? doubled - 50 : doubled;
}

Advanced Function Concepts

Higher-Order Functions

Functions that take other functions as arguments or return functions.

const numbers = [1, 2, 3, 4];
numbers.map(x => x * 2); // [2, 4, 6, 8]

Closures

Inner functions have access to outer function variables.

function outer(x) {
  return function(y) { return x + y; };
}

Callback Functions

Functions passed as arguments to be called later.

setTimeout(() => {
  console.log("Called later");
}, 1000);

Pure Functions

Same input always produces same output, no side effects.

const add = (a, b) => a + b;
// Always returns same result

Functions — step by step

1 / 4
1

First-class functions — functions as values

In JavaScript, functions are first-class citizens: they can be stored in variables, passed as arguments, returned from other functions, and added as object properties. This enables higher-order functions (map, filter, reduce), callbacks, closures, and the entire functional programming paradigm in JavaScript.

1 of 4
🔍Arrow functions do not have their own this
Arrow functions capture this from their enclosing lexical scope at definition time. They cannot be used as constructors (new arrowFn() throws) and do not have their own arguments object. This makes them ideal for callbacks and closures, but unsuitable for method definitions that need their own this context.

🎯 Quick Check

What is the key difference between function declarations and function expressions regarding hoisting?

JavaScript Functions: summary

Key points

  • A function without a return returns undefined.
  • Function declarations are hoisted, so you can call them before they appear in the file; function expressions and arrow functions aren't.
  • Parameters can have defaults (b = 1) and collect extra arguments with rest syntax (...args).
  • Keep functions small and named for what they do: calculateTotal, isValidEmail.

Frequently asked questions

›What is the difference between parameters and arguments?

Parameters are the names in the function definition (a, b). Arguments are the actual values you pass when calling it (2, 3).

›What is a callback function?

A function passed to another function to be called later, like the function you give to addEventListener or array.map.