Skip to main content
โš™๏ธbeginner

Function Basics

Functions are the building blocks of JavaScript programs. Learn declarations, expressions, arrow functions, parameters, and return values.

What is a Function?

A function is a reusable block of code that performs a specific task. You define it once and can call it as many times as you need.

hljs javascript
// Define the function
function greet(name) {
  return "Hello, " + name + "!";
}

// Call it
console.log(greet("Alice"));  // "Hello, Alice!"
console.log(greet("World"));  // "Hello, World!"

Functions help you:

  • Avoid repeating yourself (DRY principle)
  • Give meaningful names to logic
  • Test and debug code in isolation

Function Declarations

The classic way to define a function:

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

console.log(add(2, 3)); // 5

Key property: Function declarations are hoisted โ€” you can call them before they're defined in the file:

hljs javascript
sayHello(); // Works!

function sayHello() {
  console.log("Hello!");
}

Function Expressions

Assign a function to a variable:

hljs javascript
const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(4, 5)); // 20

// Named function expression (useful for recursion and stack traces)
const factorial = function fact(n) {
  return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5)); // 120

Function expressions are not hoisted โ€” you must define them before calling:

hljs javascript
// sayHi(); // TypeError: sayHi is not a function

const sayHi = function() {
  console.log("Hi!");
};

sayHi(); // Works now

Arrow Functions

Introduced in ES6, arrow functions are a concise syntax for function expressions:

hljs javascript
// Standard function
const square = function(x) {
  return x * x;
};

// Arrow function โ€” equivalent
const square = (x) => {
  return x * x;
};

// Implicit return (when body is a single expression)
const square = x => x * x;

console.log(square(5)); // 25

More examples:

hljs javascript
const add = (a, b) => a + b;
const greet = name => `Hello, ${name}!`;
const getPI = () => 3.14159;

// Multi-line body needs explicit return
const processUser = (user) => {
  const { name, age } = user;
  return `${name} is ${age} years old`;
};

โš ๏ธArrow functions and this

Arrow functions don't have their own this context โ€” they inherit it from the surrounding scope. This is a key difference from regular functions, covered in detail in the this keyword lesson.

Parameters and Arguments

Parameters are the names listed in the function definition. Arguments are the values passed when calling.

hljs javascript
function introduce(firstName, lastName) {  // parameters
  return `I'm ${firstName} ${lastName}`;
}

introduce("John", "Doe");  // arguments

Default Parameters

hljs javascript
function greet(name = "World", punctuation = "!") {
  return `Hello, ${name}${punctuation}`;
}

greet();              // "Hello, World!"
greet("Alice");       // "Hello, Alice!"
greet("Bob", ".");    // "Hello, Bob."

Rest Parameters

Collect any number of arguments into an array:

hljs javascript
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

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

// Rest must be the last parameter
function log(level, ...messages) {
  console.log(`[${level}]`, ...messages);
}
log("INFO", "User logged in", "ID:", 42);

Return Values

Every function returns a value. If no return statement, it returns undefined:

hljs javascript
function noReturn() {
  console.log("I don't return anything");
}
const result = noReturn(); // result is undefined

function getUser() {
  return { name: "Alice", age: 30 };
}
const user = getUser(); // { name: "Alice", age: 30 }

Returning early:

hljs javascript
function divide(a, b) {
  if (b === 0) return null; // early return for invalid input
  return a / b;
}

console.log(divide(10, 2));  // 5
console.log(divide(10, 0));  // null

First-Class Functions

In JavaScript, functions are values โ€” they can be stored in variables, passed as arguments, and returned from other functions:

hljs javascript
// Store in a variable
const greet = (name) => `Hi, ${name}!`;

// Pass as an argument (callback)
const names = ["Alice", "Bob", "Charlie"];
names.forEach(name => console.log(greet(name)));

// Return from a function (higher-order function)
function makeMultiplier(factor) {
  return (number) => number * factor;
}

const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5));  // 10
console.log(triple(5));  // 15

Pure Functions

A pure function always returns the same output for the same input and has no side effects:

hljs javascript
// โœ“ Pure
function add(a, b) {
  return a + b;
}

// โœ— Impure โ€” modifies external state
let total = 0;
function addToTotal(n) {
  total += n; // side effect!
  return total;
}

// โœ— Impure โ€” depends on external state
function getFullName() {
  return window.firstName + " " + window.lastName;
}

โœ…Tip

Aim to write pure functions when possible. They're predictable, easy to test, and safe to reuse.

โ–ถTry it yourself

Key Takeaways

  • Function declarations are hoisted; function expressions are not
  • Arrow functions are concise and don't have their own this
  • Use default parameters to handle missing arguments
  • Rest parameters (...args) collect unlimited arguments into an array
  • Functions are first-class โ€” pass them around like any other value
  • Pure functions are predictable and easy to test

Ready to test your knowledge?

Take a quiz on what you just learned.

Take the Quiz โ†’