Code of the Day
BeginnerLanguage basics

Functions

Declarations, arrow functions, parameters, and return values.

JavaScript / TSBeginner9 min read
Recommended first
By the end of this lesson you will be able to:
  • Define functions as declarations and as arrow functions
  • Use parameters, defaults, and return values
  • Pass functions as values

Functions are the unit of reuse (the decomposition fundamentals lesson). JavaScript has two main ways to write them, and you'll read both constantly.

Two ways to write a function

A declaration uses the function keyword; an is a shorter form assigned to a variable:

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

const addArrow = (a, b) => {
  return a + b;
};

// for a single expression, an arrow can be even shorter — the result is returned:
const addShort = (a, b) => a + b;

All three compute the same thing. Arrow functions are popular for short callbacks; declarations read well for named, standalone logic. (They differ in subtle ways around this, which matters later with classes — for now, treat them as two spellings.) When a function captures variables from its surrounding scope it forms a .

Parameters, defaults, return

Parameters can have defaults, and return hands a value back:

function greet(name, greeting = "Hello") {
  return greeting + ", " + name + "!";
}
greet("Ada");            // "Hello, Ada!"
greet("Ada", "Hi");      // "Hi, Ada!"

A function with no return (or a bare return) gives back undefined.

JavaScript — editable, runs in your browser

Functions are values

As you saw with binding, functions are ordinary values — you can store them and pass them to other functions. This is what makes array methods like map work:

const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);   // [2, 4, 6]

map takes a function and calls it on each element — passing behaviour as data.

Where to go next

Next: control flow — conditionals and loops to drive your functions.

Finished reading? Mark it complete to track your progress.

On this page