JavaScript Course Lesson 13 of 16
The Codex / JavaScript / Functions

Functions

Reusable blocks of code — declarations, expressions, arrow functions, default parameters, and first-class functions.

What it is, in plain English: A function is a named, reusable block of code that does one specific job. You define it once, then call it as many times as you need. JavaScript has three ways to write a function: declarations, expressions, and arrow functions. Arrow functions are the modern choice for short callbacks; regular functions are needed when you use 'this'. In JavaScript, functions are values — you can store them in variables, pass them to other functions, and return them from functions.

Writing reusable code with functions

Imagine you need to calculate a discount on a price. You write the calculation once. Then you need to apply it to 50 products. Without functions, you'd copy-paste the same calculation 50 times. With a function, you write it once and call it 50 times. Functions are the fundamental unit of reusability.

Three ways to write a function

1. Function declaration — the traditional way:

function calculateDiscount(price, discountPercent) {
  const discount = price * (discountPercent / 100);
  return price - discount;
}

console.log(calculateDiscount(100, 20));  // 80
console.log(calculateDiscount(50, 10));   // 45

2. Function expression — assigned to a variable:

const calculateTax = function(price, rate) {
  return price * rate;
};

console.log(calculateTax(100, 0.18));  // 18

3. Arrow function — modern, concise, preferred for short functions:

// Full arrow function:
const greet = (name) => {
  return `Hello, ${name}!`;
};

// Shorthand: single expression — no braces, no return needed
const greetShort = (name) => `Hello, ${name}!`;

// Single parameter — parentheses optional
const double = n => n * 2;

// No parameters — empty parentheses required
const getRandom = () => Math.random();

console.log(greet("Alice"));       // "Hello, Alice!"
console.log(double(7));            // 14
console.log(getRandom());          // some random number

When to use which

  • Arrow functions for callbacks and short operations: array.map(x => x * 2)
  • Function declarations for named, top-level functions you'll call from many places
  • Avoid function expressions in most cases — arrow functions do the same with less code

Parameters and arguments

// Parameters are the names in the definition:
function add(a, b) {   // a and b are parameters
  return a + b;
}

// Arguments are the actual values you pass when calling:
add(3, 5);   // 3 and 5 are arguments

Default parameters

// If an argument is missing, use the default value:
function createUser(name, role = "viewer", isActive = true) {
  return { name, role, isActive };
}

console.log(createUser("Alice", "admin"));
// { name: "Alice", role: "admin", isActive: true }

console.log(createUser("Bob"));
// { name: "Bob", role: "viewer", isActive: true }  — defaults used

Rest parameters — variable number of arguments

// ...name collects all extra arguments into an array:
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2));          // 3
console.log(sum(1, 2, 3, 4, 5)); // 15
console.log(sum());               // 0

return — sending a value back

function isAdult(age) {
  return age >= 18;   // sends true or false back to the caller
}

const result = isAdult(20);
console.log(result);   // true

// A function without return gives back undefined:
function logMessage(msg) {
  console.log(msg);
  // no return — returns undefined
}
console.log(logMessage("hi"));  // logs "hi", then logs undefined

Functions are values — first-class functions

This is one of JavaScript's most important ideas: functions are values, just like numbers and strings. You can store them in variables, put them in arrays, pass them to other functions, and return them from functions.

// Store in a variable (already seen):
const greet = name => `Hello, ${name}!`;

// Pass to another function (callback):
const names = ["Alice", "Bob", "Charlie"];
const greeted = names.map(name => `Hello, ${name}!`);
console.log(greeted);
// ["Hello, Alice!", "Hello, Bob!", "Hello, Charlie!"]

// A function that takes another function as a parameter:
function doTwice(fn, value) {
  return fn(fn(value));
}
const addTen = n => n + 10;
console.log(doTwice(addTen, 5));   // 25  (5 → 15 → 25)
Try It Yourself

Official Sources

The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.