What is a function in JavaScript?

A function is a callable object that wraps reusable logic; in JavaScript functions are first-class values, so they can be stored in variables, passed as arguments, returned from other functions and given properties.

Ways to create one

  • Function declaration: function add(a, b) {}. Hoisted, has its own this and arguments.
  • Function expression: const add = function (a, b) {}. Not usable before the line it is defined on.
  • Arrow function: const add = (a, b) => a + b. Shorter, no own this, arguments or prototype, cannot be used with new.
  • Method shorthand: { add(a, b) {} } inside objects and classes.
  • Also: generator functions (function*), async functions and class constructors.

Parameters

  • Default values: function greet(name = "friend").
  • Rest parameters: function sum(...nums) collects extra arguments into an array.
  • Missing arguments are undefined; extra ones are ignored.

Why "first-class" matters

Because functions are values, JavaScript supports callbacks, higher-order functions (map, filter), closures, and patterns like middleware and event handlers.

Return values

A function without a return (or with a bare return) returns undefined.

Code example

js
1// Declaration (hoisted)
2function add(a, b = 0) {
3 return a + b;
4}
5
6// Expression and arrow
7const multiply = function (a, b) {
8 return a * b;
9};
10const square = (n) => n * n;
11
12// Rest parameters
13const sum = (...nums) => nums.reduce((total, n) => total + n, 0);
14
15// Functions are values: pass them and return them
16const apply = (fn, ...args) => fn(...args);
17const makeGreeter = (greeting) => (name) => `${greeting}, ${name}!`;
18
19console.log(add(2)); // 2
20console.log(multiply(3, 4)); // 12
21console.log(apply(square, 5)); // 25
22console.log(sum(1, 2, 3, 4)); // 10
23console.log(makeGreeter("Hello")("Ada")); // Hello, Ada!
24
25// Functions are objects, so they have properties
26console.log(add.name, add.length); // "add" 1 (params before the first default)

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app