KodingKaro
JavaScript · Beginner · Functions

Callbacks for reusable behavior

This lesson applies Functions concepts to code you can run and adapt.

✓ What you will learn in this topic

  • Explain key Functions concepts.
  • Read and adapt the examples.
  • Apply the idea to a small real interface or data task.

Concept explanation

Function declarations and expressions, arrow functions, parameters, arguments, returns, defaults, rest, scope, and callbacks.

These concepts appear in everyday interfaces and data transformations; understanding the trade-offs helps you choose a reliable implementation.

Syntax

The examples use standard ECMAScript syntax. Run console examples in a browser console or Node.js; DOM examples require a browser page containing the referenced elements.

Example 1: a small experiment

Run this compact example to observe the core rule before applying it to a larger feature.

const prices = [5, 9];
const withTax = prices.map((price) => price * 1.1);
console.log(withTax);

Expected output: [5.5, 9.9]

Why it is useful: A small experiment makes the value or behavior easy to inspect.

Example 2: a practical feature

This example models a small piece of application behavior. Adapt its values and inspect what changes.

function addTax(amount, rate = 0.1) {
  return amount * (1 + rate);
}
console.log(addTax(20));

Expected output: 22

Why it is useful: The same pattern can be extended into a real feature without tying the entire application to one large block of code.

Common mistakes

An arrow function does not create its own this. Do not replace an object method with an arrow when it needs method-call this.

Best practices

Return values instead of printing from reusable calculations. Use callbacks to pass behavior to another function.

Practice exercise

Write a reusable function that accepts any number of scores and returns their average.

Lesson summary

Function declarations and expressions, arrow functions, parameters, arguments, returns, defaults, rest, scope, and callbacks.

Knowledge check

Which practice best avoids the common mistake in Functions?

Show explanation

Return values instead of printing from reusable calculations. Use callbacks to pass behavior to another function.

Practical example

javascript
function addTax(amount, rate = 0.1) {
  return amount * (1 + rate);
}
console.log(addTax(20));

Expected result:

22

Hands-on practice task

Write a reusable function that accepts any number of scores and returns their average.

In this section

Other lessons in Functions

Broaden your knowledge

Related learning topics