Functions and Arrow Functions

Site Admin · 11 Sep 2026 · 6 views

Functions and Arrow Functions

Functions are the core building blocks of JavaScript. They package reusable logic, accept inputs, and return outputs. ES6 added arrow functions with cleaner syntax and different this behavior.

Function Declarations and Expressions

// Function declaration (hoisted)
function greet(name) {
    return `Hello, ${name}!`;
}

// Function expression
const square = function(x) {
    return x * x;
};

// Arrow function (ES6)
const double = (x) => x * 2;

// Arrow function with no parentheses for one parameter
const isEven = x => x % 2 === 0;

// Arrow function with multiple parameters
const add = (a, b) => a + b;

Default Parameters

function greet(name = "stranger") {
    return `Hello, ${name}!`;
}

greet();          // "Hello, stranger!"
greet("Bob");     // "Hello, Bob!"

Rest Parameters

function sum(...numbers) {
    return numbers.reduce((total, n) => total + n, 0);
}

sum(1, 2, 3);        // 6
sum(1, 2, 3, 4, 5);  // 15

The this Keyword

Arrow functions do not have their own this. They inherit it from the surrounding scope. This makes them ideal for array callbacks and event handlers where you want the outer context.

const user = {
    name: "Alice",
    hobbies: ["Reading", "Cycling"],
    // Regular function: this refers to the object
    describe() {
        return `My name is ${this.name}`;
    },
    // Arrow function inherits this from describe
    listHobbies() {
        return this.hobbies.map(hobby => `${this.name} likes ${hobby}`);
    }
};

Higher-Order Functions

Functions that take functions as arguments or return them are higher-order functions. Array methods like map, filter, and reduce are the most common examples:

const prices = [10, 25, 50, 75];

const discounted = prices.map(p => p * 0.9);        // [9, 22.5, 45, 67.5]
const cheap = prices.filter(p => p < 60);           // [10, 25, 50]
const total = prices.reduce((sum, p) => sum + p, 0); // 160

Key Points

  • Functions are declared with the function keyword or as expressions.
  • Arrow functions (x) => x * 2 offer concise syntax.
  • Arrow functions inherit this from the surrounding scope.
  • Default parameters and rest parameters add flexibility.
  • map, filter, and reduce are powerful higher-order functions.
Share this post:

Comments (0)

Please login or register to comment.