Programación Para Tontos

JavaScript

Tutorial: functions in JavaScript - package up reusable code

Learn to declare and use JavaScript functions by building a small tip calculator.

A function is a little box of instructions that you give a name to, so you don't have to rewrite it every time. Today you'll build a tip calculator (useful, unlike most "hello world" examples).

Step 1: declare your first function

function calculateTip(bill, percentage) {
  return bill * (percentage / 100);
}

console.log(calculateTip(200, 15)); // 30

function name(parameters) { ... } is the classic way to declare a function. bill and percentage are parameters: values you "lend" the function each time you use it.

Step 2: use a default value

function calculateTip(bill, percentage = 10) {
  return bill * (percentage / 100);
}

console.log(calculateTip(200)); // 20 (uses 10% by default)
console.log(calculateTip(200, 20)); // 40

If you don't pass percentage, JavaScript uses the default value instead of giving you undefined. Fewer bugs, less drama.

Step 3: the modern version - arrow functions

const calculateTotal = (bill, tip) => bill + tip;

console.log(calculateTotal(200, 30)); // 230

Arrow functions (=>) are a shorter way to write functions, very common in modern code. When the body is a single expression, you don't even need return or curly braces.

Step 4: put it all together

function billSummary(bill, tipPercentage = 10) {
  const tip = calculateTip(bill, tipPercentage);
  const total = calculateTotal(bill, tip);
  return `Bill: $${bill}, tip: $${tip}, total: $${total}`;
}

console.log(billSummary(500, 18));

A function can call other functions. This is how "big" code is actually a bunch of small functions working together, not one genius typing 500 lines in one sitting.

What did you just learn?

  • How to declare functions with parameters and default values.
  • The modern arrow function syntax.
  • That functions can be combined to solve bigger problems.