JavaScript:JavaScript Functions: Arrow Functions, Parameters, and Rest
JavaScript•Functions

JavaScript Functions: Arrow Functions, Parameters, and Rest

Learn modern function syntax, lexical this binding in arrow functions, default arguments, and rest/spread.

Syntax

function fn(a, b = 10) { return a + b; } const arrowFn = (a, b) => a + b;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
arrow function =>SyntaxConcise function expression that lexically binds this.
...argsRest ParameterCollects indefinite arguments into a single array.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// Arrow Functions and Rest Parameters
const calculateInvoice = (taxRate = 0.08, ...prices) => {
  const subtotal = prices.reduce((acc, p) => acc + p, 0);
  const tax = subtotal * taxRate;
  const total = subtotal + tax;
  return {
    subtotal: subtotal.toFixed(2),
    tax: tax.toFixed(2),
    total: total.toFixed(2)
  };
};

const invoice = calculateInvoice(0.10, 19.99, 49.50, 25.00);
console.log("Invoice Summary:");
console.log("  Subtotal: $" + invoice.subtotal);
console.log("  Tax (10%): $" + invoice.tax);
console.log("  Total:     $" + invoice.total);
Expected Output:
Invoice Summary:
  Subtotal: $94.49
  Tax (10%): $9.45
  Total:     $103.94

How It Works: Step-by-Step

  • Lines 2-10: Uses arrow function with default parameter and rest parameter ...prices.
  • Line 12: Passes arbitrary price arguments collected into prices array.

Key Concepts

  • Arrow functions do not bind their own this, arguments, super, or new.target.
  • Rest parameters (...args) must be the last parameter in the function signature.
  • Functions are first-class citizens in JavaScript and can be passed as arguments or returned.

Common Mistake: Using arrow functions as object methods when this is required

Arrow functions do not bind this to the calling object; this remains bound to lexical scope (often window or undefined).

❌ Incorrect
const obj = { count: 0, inc: () => { this.count++; } }; // this is NOT obj!
✅ Correct
const obj = { count: 0, inc() { this.count++; } }; // Correct standard method

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler