Functions

Functions are reusable blocks of code you can call by name.

Syntaxfunction name() { ... } name();

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

Declaring and calling

Use the function keyword, a name, parentheses, and a body in braces. Call it by writing its name followed by ().

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Encapsulate a tax calculation so it can be called from multiple places in a checkout module.
  • Define a reusable greeting function that the marketing page calls for each visitor segment.
  • Wrap repeated DOM manipulation steps into a named function to keep event handlers short.

More examples

Declare and call a function

Declares a named function and calls it twice with different arguments.

Example · js
function greet(name) {
  console.log("Hello, " + name + "!");
}
greet("Alice"); // Hello, Alice!
greet("Bob");   // Hello, Bob!

Function expression stored in variable

Assigns an anonymous function expression to a const variable and calls it by that variable name.

Example · js
const square = function (n) {
  return n * n;
};
console.log(square(5)); // 25

Reusable tax calculator

Defines a function that computes a tax-inclusive total, making it reusable across the checkout flow.

Example · js
function calculateTotal(price, taxRate) {
  return price + price * taxRate;
}
const total = calculateTotal(49.99, 0.08);
console.log(total.toFixed(2)); // "53.99"

Discussion

  • Be the first to comment on this lesson.
Functions — JavaScript | SoundsCode