CodeMIRAI
0 XP

Functions

2 min read 7 runnable examples Quiz included

A function is a reusable block of code. You define it once and call it whenever you need it.

Function declarations

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

console.log(greet("Asha"));
console.log(greet("Leo"));
  • name is a parameter; "Asha" is an argument.
  • return sends a value back to the caller and ends the function.
  • A function without return gives back undefined.

Default parameters

JavaScript
function power(base, exponent = 2) {
  return base ** exponent;
}
console.log(power(5));
console.log(power(2, 10));

Missing arguments are undefined unless they have a default:

JavaScript
function add(a, b) {
  return a + b;
}
console.log(add(2));     // 2 + undefined = NaN

Returning early

JavaScript
function shippingCost(total) {
  if (total >= 500) return 0;      // free shipping
  if (total >= 200) return 20;
  return 50;
}
console.log(shippingCost(650), shippingCost(250), shippingCost(80));

Function expressions

A function can also be stored in a variable:

JavaScript
const square = function (n) {
  return n * n;
};
console.log(square(9));

Hoisting

Function declarations are "hoisted": you can call them before the line where they're defined. Function expressions are not:

JavaScript
console.log(double(4));      // works: declarations are hoisted
function double(n) { return n * 2; }

console.log(triple(4));      // fails: triple isn't defined yet
const triple = function (n) { return n * 3; };

Rest parameters

... collects any number of arguments into an array:

JavaScript
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3), sum(10, 20, 30, 40), sum());
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.