学习库JavaScriptFunctions

Functions

Package behavior with parameters, return values, scope, and predictable side effects.

更新于 适用于 ECMAScript 2026

Functions turn a sequence of operations into a named, reusable unit. A focused function accepts what it needs and returns a result the caller can use.

Parameters and returns

progress.js
function progressPercent(completed, total) {
  if (total <= 0) return 0;
  return Math.round((completed / total) * 100);
}

const progress = progressPercent(6, 8);

Parameters are local names. return ends the call and sends a value back; without it, the result is undefined.

Function expressions and arrows

formats.js
const formatCourse = function (name) {
  return name.trim().toUpperCase();
};

const double = (number) => number * 2;

Arrow functions are concise and capture this from the surrounding scope. Regular functions are better when a method needs a dynamic this value.

Pure logic and side effects

price.js
function totalWithTax(subtotal, taxRate) {
  return subtotal * (1 + taxRate);
}

function announce(message) {
  console.log(message);
}

The first function is pure: the same input produces the same output without changing outside state. The second has a side effect. Keeping calculation separate from effects makes code easier to test.

Keep this

Keep functions small, return useful values, validate edge cases, and separate calculations from external effects.

学习位置已保存在此设备上。