DevPath · Learn to code ESPTEN

Functions

Parameters, default values and return

Parameters and arguments

function multiply(a, b) { // a and b are parameters
  return a * b;
}
multiply(3, 4); // 3 and 4 are arguments

Default values

You can give a parameter a default value in case it is not provided:

function greet(name = "friend") {
  return "Hello, " + name;
}
console.log(greet());       // "Hello, friend"
console.log(greet("Lucia")); // "Hello, Lucia"

return

The keyword return returns a value and ends the function immediately.

⚠️ Classic trap: forgetting the return. A function without return always gives back undefined, no matter how many calculations it runs inside. If your function "returns nothing", check this first: it's the number-one mistake for beginners.

function isAdult(age) {
  if (age >= 18) {
    return true;  // exits here
  }
  return false;
}

Anything you write after an executed return never runs.

Examples

Calculating a discounted price: default value and early return

function finalPrice(price, discount = 0) {
  if (price <= 0) return 0;
  return price - price * discount;
}
console.log(finalPrice(100));      // 100
console.log(finalPrice(100, 0.2)); // 80
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Arrow functionsFunctions as values →