Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Functions: Core to Advanced Patterns

Functions are the foundation of reusable and testable JavaScript. Strong function design directly improves architecture quality.

Why this matters

Most business logic is implemented through functions. Understanding syntax and behavior prevents many runtime issues.

Function Declaration, Expression, and Arrow

Function declarations are hoisted with implementation. Function expressions depend on assignment timing.

Arrow functions provide concise syntax and lexical this. They are useful for callbacks but not always suitable for methods.

Choose style based on behavior needs, not only syntax preference.

Parameters and Return Design

Use default parameters to prevent undefined edge cases and rest parameters for flexible argument counts.

Return explicit values from utility functions to avoid hidden undefined behavior in chains.

Code Examples

Declaration and Expression

console.log(add(2, 3)); // 5
function add(a, b) {
  return a + b;
}

const subtract = function (a, b) {
  return a - b;
};
console.log(subtract(8, 3));

Declaration hoists fully, expression does not.

Arrow Function and this

const profile = {
  name: "Nina",
  normal() {
    return this.name;
  },
  arrow: () => this?.name,
};

console.log(profile.normal()); // Nina
console.log(profile.arrow()); // usually undefined

Arrow functions inherit outer this, so avoid them for object methods needing local context.

Default and Rest Parameters

function invoice(tax = 0.18, ...amounts) {
  const subtotal = amounts.reduce((sum, n) => sum + n, 0);
  return subtotal + subtotal * tax;
}

console.log(invoice(0.18, 120, 80, 50));

Cleaner APIs with default values and flexible argument handling.

Common Mistakes and Fixes

Using arrow for method requiring this

Use method syntax or function keyword for dynamic this binding.

Large functions with many responsibilities

Split into smaller composable helpers with clear input-output.

Implicit undefined returns

Return explicit output in utility functions.

Frequently Asked Questions

Are arrow functions always better?

No. They are concise, but not ideal where method-level this behavior is required.

What is a higher-order function?

A function that accepts another function or returns one.

Can function declarations be used before definition?

Yes, due to hoisting behavior.

Should I use default parameters often?

Yes, when sensible defaults prevent undefined edge-case bugs.

Related JavaScript Topics