JavaScript and TypeScript course · Module 2: Functions, Arrays and Objects

Arrow Functions

9 min read ·
In this lesson7

Welcome back to Jurassic Park! Today we will get to know arrow functions - a modern way of creating functions in JavaScript that was introduced in ES6. Arrow functions are more concise than traditional function expressions and have a few unique properties that make them extremely useful in everyday work.

Basic Syntax of Arrow Functions

Arrow functions have a more concise syntax than traditional functions. Let's compare:

Traditional function:

// Traditional anonymous function
const identifyDinosaur = function(species) {
  return "Species identified: " + species;
};

Arrow function:

// Arrow function
const identifyDinosaur = (species) => {
  return "Species identified: " + species;
};

We can see that the arrow function:

  1. Does not use the function keyword
  2. Uses the arrow sign => between the parameters and the function body

Even More Concise

Arrow functions offer an even shorter syntax in the following cases:

One parameter: you can omit the parentheses

// With parentheses
const getSpeciesInfo = (species) => {
  return `The species ${species} was found in the database.`;
};

// Without parentheses - the same thing
const getSpeciesInfoShort = species => {
  return `The species ${species} was found in the database.`;
};

One-line function: implicit return

If the function body consists of only a single expression that returns a value, we can omit the curly braces and the return keyword:

// With return
const getSpeciesAge = (species) => {
  return species === "Tyrannosaurus" ? "68 million years" : "Age unknown";
};

// With an implicit return - the same thing
const getSpeciesAgeShort = (species) => species === "Tyrannosaurus" ? "68 million years" : "Age unknown";

Returning an object

When returning an object, we have to put parentheses around it so that it is not interpreted as a block of code:

// Incorrect - JavaScript will think it is a block of code
// const getDinoData = (name, species) => { name: name, species: species };

// Correct - the object is wrapped in parentheses
const getDinoData = (name, species) => ({ name: name, species: species });

const blue = getDinoData("Blue", "Velociraptor");
console.log(blue); // { name: "Blue", species: "Velociraptor" }

Practical Uses of Arrow Functions

1. Processing Data Collections

Arrow functions are especially handy with array methods such as map, filter, reduce:

// List of dinosaurs
const dinosaurs = [
  { name: "Rex", species: "Tyrannosaurus", carnivore: true, weight: 7000 },
  { name: "Spike", species: "Stegosaurus", carnivore: false, weight: 5000 },
  { name: "Blue", species: "Velociraptor", carnivore: true, weight: 100 },
  { name: "Trixie", species: "Triceratops", carnivore: false, weight: 8000 }
];

// Filtering the carnivores
const carnivores = dinosaurs.filter(dino => dino.carnivore);

// Mapping to species names
const speciesList = dinosaurs.map(dino => dino.species);

// Calculating the total weight of all dinosaurs
const totalWeight = dinosaurs.reduce((sum, dino) => sum + dino.weight, 0);

console.log("Carnivores:", carnivores.length);
console.log("Species:", speciesList.join(", "));
console.log("Total weight:", totalWeight, "kg");

2. Objects with Methods

Arrow functions come in handy inside object methods, for example as callbacks in setInterval, because they keep the method's this (more on that a little later):

const dinoMonitor = {
  dinosaurs: ["T-Rex", "Velociraptor", "Triceratops"],
  lastUpdated: null,

  init() {
    this.update();

    // Schedule an update every 60 seconds
    setInterval(() => {
      this.update();
      console.log("Monitor updated");
    }, 60000);
  },

  update() {
    this.lastUpdated = new Date().toISOString();
    console.log(`Monitored dinosaurs: ${this.dinosaurs.join(", ")}`);
  }
};

dinoMonitor.init();

The Key Difference: How this Behaves

The most important difference between arrow functions and traditional functions is the way they bind the this context.

Traditional functions: dynamic this binding

In traditional functions, this is determined at the moment the function is called, and it can change:

function DinoTracker() {
  this.zone = "Unknown";

  this.updateZone = function(newZone) {
    this.zone = newZone;
    console.log(`Zone: ${this.zone}`);
  };

  // Problem: 'this' in a regular function passed to setInterval does not point to DinoTracker (in the browser it is window, in Node.js a Timeout object)
  setInterval(function() {
    console.log(`Current zone: ${this.zone}`); // undefined
  }, 1000);
}

const tracker = new DinoTracker();
tracker.updateZone("Enclosure A");

Arrow functions: lexical this binding

Arrow functions do not have their own this. Instead, they inherit this from the scope in which they were defined (so-called lexical binding):

function DinoTracker() {
  this.zone = "Unknown";

  this.updateZone = function(newZone) {
    this.zone = newZone;
    console.log(`Zone: ${this.zone}`);
  };

  // Solution: the arrow function keeps 'this' from the surrounding scope
  setInterval(() => {
    console.log(`Current zone: ${this.zone}`); // It works!
  }, 1000);
}

const tracker = new DinoTracker();
tracker.updateZone("Enclosure A");

When NOT to Use Arrow Functions

Despite their advantages, arrow functions are not suitable for every situation:

1. Object methods (when we need our own this)

// WRONG - an arrow function has no 'this' of its own
const dinoBad = {
  name: "Blue",
  introduce: () => {
    console.log(`Hi, I'm ${this.name}`); // this does not point to the dino object, so you will not see the name Blue here
  }
};

// CORRECT - a traditional function has its own 'this' context
const dinoGood = {
  name: "Blue",
  introduce: function() {
    console.log(`Hi, I'm ${this.name}`); // It works!
  }
};

// CORRECT - the ES6 shorthand method syntax
const dinoShort = {
  name: "Blue",
  introduce() {
    console.log(`Hi, I'm ${this.name}`); // It works too!
  }
};

2. Constructor functions (when we use new)

// WRONG - arrow functions cannot be constructors
const DinosaurArrow = (name, species) => {
  this.name = name;
  this.species = species;
};

// This will cause an error:
// const rex = new DinosaurArrow("Rex", "Tyrannosaurus");

// CORRECT - a traditional function as a constructor
function Dinosaur(name, species) {
  this.name = name;
  this.species = species;
}

const rex = new Dinosaur("Rex", "Tyrannosaurus");
console.log(rex); // Dinosaur { name: "Rex", species: "Tyrannosaurus" }

3. When we need the arguments object

// WRONG - arrow functions do not have their own 'arguments' object
const logArgsArrow = () => {
  console.log(arguments); // ReferenceError or the arguments of the enclosing function
};

// CORRECT - a traditional function has its own 'arguments' object
function logArgsRegular() {
  console.log(arguments); // an array-like object with the arguments
}

// Alternatively in ES6 - use the rest parameter
const logArgsRest = (...args) => {
  console.log(args); // an array with the arguments
};

Practical Example: A Park Monitoring System

Let's build a complete example of a Jurassic Park monitoring system, making use of arrow functions and their unique properties:

const parkMonitoringSystem = {
  // System state
  status: "Offline",
  dinosaurs: [],
  sectors: [],
  securityAlerts: [],

  // System initialization
  initialize() {
    this.status = "Starting";

    // Helper function that preserves the this context
    const loadConfigs = () => {
      // Simulating configuration loading
      console.log("Loading system configuration...");

      // Using this from the outer scope
      setTimeout(() => {
        this.status = "Online";
        this.dinosaurs = [
          { id: "TRX-01", name: "Rex", species: "Tyrannosaurus", location: "Sector A", status: "OK" },
          { id: "VLR-01", name: "Blue", species: "Velociraptor", location: "Sector B", status: "OK" },
          { id: "TRC-01", name: "Trixie", species: "Triceratops", location: "Sector C", status: "OK" }
        ];
        this.sectors = ["A", "B", "C", "D"];

        console.log(`System online. Dinosaurs monitored: ${this.dinosaurs.length}`);
        this.startMonitoring();
      }, 2000);
    };

    loadConfigs();
  },

  // Starting the monitoring
  startMonitoring() {
    this.checkSecurity();

    // Checking the status every 5 minutes
    setInterval(() => this.checkStatus(), 300000);

    // Collecting dinosaur data every hour
    setInterval(() => this.collectData(), 3600000);

    console.log("Monitoring started");
  },

  // Checking the status of the dinosaurs
  checkStatus() {
    const timestamp = new Date().toISOString();

    // Using map with an arrow function
    const statusReport = this.dinosaurs.map(dino => ({
      id: dino.id,
      name: dino.name,
      status: dino.status,
      location: dino.location,
      timestamp
    }));

    console.log("Dinosaur status report:", statusReport);
    return statusReport;
  },

  // Checking security
  checkSecurity() {
    console.log("Checking the park's security status...");

    // Using filter with an arrow function
    const compromisedSectors = this.sectors.filter(sector =>
      Math.random() < 0.1 // 10% chance of a problem in each sector (simulation)
    );

    if (compromisedSectors.length > 0) {
      // Using forEach with an arrow function
      compromisedSectors.forEach(sector => {
        const alert = {
          id: `ALERT-${Date.now()}`,
          sector,
          type: "Security breach",
          timestamp: new Date().toISOString()
        };

        this.securityAlerts.push(alert);
        this.triggerAlert(alert);
      });
    } else {
      console.log("All sectors secure");
    }
  },

  // Triggering an alert
  triggerAlert(alert) {
    console.log(`ALERT! ${alert.type} in sector ${alert.sector}!`);

    // Calling the appropriate procedures
    this.notifySecurityTeam(alert);
  },

  // Notifying the security team
  notifySecurityTeam(alert) {
    const securityPersonnel = ["John Hammond", "Robert Muldoon", "Ray Arnold"];

    // Using an arrow function to create the message
    const createMessage = person => `Notifying ${person} about the alert in sector ${alert.sector}`;

    // Sending the message to each team member
    securityPersonnel.forEach(person => {
      console.log(createMessage(person));
    });
  },

  // Collecting dinosaur data
  collectData() {
    console.log("Collecting dinosaur data...");

    // Using reduce with an arrow function
    const speciesCount = this.dinosaurs.reduce((counts, dino) => {
      counts[dino.species] = (counts[dino.species] || 0) + 1;
      return counts;
    }, {});

    console.log("Number of dinosaurs by species:", speciesCount);

    return {
      timestamp: new Date().toISOString(),
      totalCount: this.dinosaurs.length,
      speciesDistribution: speciesCount
    };
  }
};

// Starting the system
parkMonitoringSystem.initialize();

Summary

Arrow functions bring several important changes to the JavaScript language:

  1. More concise syntax - less code to write
  2. Lexical this binding - solves many problems with context
  3. Implicit return - for one-line functions

This makes them especially useful in many situations, such as:

  • Functions passed to array methods (map, filter, reduce)
  • Callback functions in timers and event handling
  • Short helper functions

At the same time, let's remember their limitations:

  • No this of their own (which is an advantage or a drawback, depending on the situation)
  • No arguments (although you can use the rest parameter)
  • They cannot be used as constructors

In our Jurassic Park, arrow functions help us write more concise and clearer code, which is extremely important when managing such a complex ecosystem. In the next modules we will use arrow functions in various contexts, which will let us understand their uses even better.

Code for this lesson: index.js
// Arrow functions - Jurassic Park
console.log("Arrow Functions Laboratory");
console.log("Modern approach to functions in JavaScript\n");

// ===========================================
// 1. BASIC SYNTAX
// ===========================================
console.log("=== 1. Arrow function syntax ===");

// Traditional function
function traditionalRoar(dino) {
  return `${dino} says: ROAAR!`;
}

// Arrow function - full syntax
const arrowRoar = (dino) => {
  return `${dino} says: ROAAR!`;
};

// Arrow function - shorthand (implicit return)
const shortRoar = dino => `${dino} says: ROAAR!`;

console.log(traditionalRoar("T-Rex"));
console.log(arrowRoar("Velociraptor"));
console.log(shortRoar("Triceratops"));

// ===========================================
// 2. DIFFERENT SYNTAX VARIANTS
// ===========================================
console.log("\n=== 2. Syntax variants ===");

// No parameters
const getDinosaurs = () => ["T-Rex", "Velociraptor", "Triceratops"];
console.log("Dinosaur list:", getDinosaurs());

// One parameter (parentheses optional)
const double = x => x * 2;
console.log("Doubling 5:", double(5));

// Multiple parameters (parentheses required)
const calculateWeight = (length, species) => length * (species === "T-Rex" ? 1000 : 500);
console.log("T-Rex weight (12m):", calculateWeight(12, "T-Rex"), "kg");

// Returning an object (requires parentheses)
const createDino = (name, species) => ({
  name: name,
  species: species,
  createdAt: new Date().toISOString()
});

console.log("\nNew dinosaur:", createDino("Blue", "Velociraptor"));

// ===========================================
// 3. COMPARISON WITH TRADITIONAL FUNCTIONS
// ===========================================
console.log("\n=== 3. Traditional vs Arrow Function ===");

// Traditional
function feedTraditional(dino) {
  console.log(`Feeding ${dino} (traditional function)`);
}

// Arrow
const feedArrow = dino => {
  console.log(`Feeding ${dino} (arrow function)`);
};

feedTraditional("T-Rex");
feedArrow("Velociraptor");

// ===========================================
// 4. ARROW FUNCTIONS WITH ARRAY METHODS
// ===========================================
console.log("\n=== 4. Arrow functions with array methods ===");

const dinosaurs = [
  { name: "Rex", species: "T-Rex", weight: 8000, carnivore: true },
  { name: "Blue", species: "Velociraptor", weight: 80, carnivore: true },
  { name: "Trike", species: "Triceratops", weight: 9000, carnivore: false },
  { name: "Brachio", species: "Brachiosaurus", weight: 50000, carnivore: false }
];

// map
const names = dinosaurs.map(dino => dino.name);
console.log("Names:", names);

// filter
const carnivores = dinosaurs.filter(dino => dino.carnivore);
console.log("\nCarnivores:", carnivores.map(d => d.name));

// reduce
const totalWeight = dinosaurs.reduce((sum, dino) => sum + dino.weight, 0);
console.log("\nTotal weight:", totalWeight, "kg");

// forEach
console.log("\nList of all dinosaurs:");
dinosaurs.forEach((dino, index) => {
  console.log(`  ${index + 1}. ${dino.name} - ${dino.species} (${dino.weight}kg)`);
});

// find
const heaviest = dinosaurs.find(dino => dino.weight > 10000);
console.log("\nHeaviest (>10000kg):", heaviest ? heaviest.name : "None");

// some & every
const hasHerbivores = dinosaurs.some(dino => !dino.carnivore);
const allCarnivores = dinosaurs.every(dino => dino.carnivore);
console.log("\nAre there herbivores?", hasHerbivores);
console.log("Are all carnivores?", allCarnivores);

// ===========================================
// 5. METHOD CHAINING
// ===========================================
console.log("\n=== 5. Method chaining ===");

const dangerousHeavyDinos = dinosaurs
  .filter(dino => dino.carnivore)
  .filter(dino => dino.weight > 100)
  .map(dino => `${dino.name} (${dino.weight}kg)`)
  .sort();

console.log("Dangerous and heavy dinosaurs:", dangerousHeavyDinos);

// ===========================================
// 6. CALLBACK FUNCTIONS
// ===========================================
console.log("\n=== 6. Arrow functions as callbacks ===");

function processDinosaurs(dinos, processor) {
  return dinos.map(processor);
}

const dinoSummaries = processDinosaurs(dinosaurs, dino =>
  `${dino.name}: ${dino.carnivore ? 'carnivore' : 'herbivore'} ${dino.weight}kg`
);

console.log("Summaries:");
dinoSummaries.forEach(summary => console.log(`  ${summary}`));

// ===========================================
// 7. ARROW FUNCTIONS IN setTimeout/setInterval
// ===========================================
console.log("\n=== 7. Arrow functions with timing functions ===");

// setTimeout with an arrow function
setTimeout(() => {
  console.log("⏰ Feeding time! (after 100ms)");
}, 100);

// Countdown simulation
let countdown = 3;
const countInterval = setInterval(() => {
  if (countdown > 0) {
    console.log(`⏳ Countdown: ${countdown}...`);
    countdown--;
  } else {
    console.log("Start!");
    clearInterval(countInterval);
  }
}, 50);

// ===========================================
// 8. DIFFERENCE IN 'this' BEHAVIOR
// ===========================================
console.log("\n=== 8. Difference in 'this' context ===");

const park = {
  name: "Jurassic Park",
  dinosaurs: ["T-Rex", "Velociraptor", "Triceratops"],

  // Method with traditional function
  displayTraditional: function() {
    console.log(`\n${this.name} - Traditional function:`);
    // this.dinosaurs.forEach(function(dino) {
    //   // this here does NOT refer to park!
    //   console.log(`  - ${dino}`);
    // });

    // Solution: arrow function in forEach
    this.dinosaurs.forEach(dino => {
      console.log(`  - ${dino} from ${this.name}`);
    });
  },

  // Method with arrow function
  displayArrow: function() {
    console.log(`\n${this.name} - Arrow function:`);
    this.dinosaurs.forEach(dino => {
      console.log(`  - ${dino} from ${this.name}`);
    });
  }
};

park.displayTraditional();
park.displayArrow();

// ===========================================
// 9. WHEN NOT TO USE ARROW FUNCTIONS
// ===========================================
console.log("\n=== 9. When NOT to use arrow functions ===");

// DO NOT use as object methods (when you need 'this')
const dinoObject = {
  name: "Rex",

  // BAD - arrow function as method
  roarBad: () => {
    // this does not point to dinoObject!
    console.log("this.name:", typeof this.name); // undefined
  },

  // GOOD - traditional function as method
  roarGood: function() {
    console.log(`${this.name} says: ROAAR!`);
  }
};

dinoObject.roarBad();
dinoObject.roarGood();

// ===========================================
// 10. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 10. Park monitoring system - complex example ===");

const parkSystem = {
  name: "Isla Nublar",
  dinosaurs: [
    { id: 1, name: "Rexy", species: "T-Rex", sector: "A", health: 95, fed: true },
    { id: 2, name: "Blue", species: "Velociraptor", sector: "B", health: 100, fed: false },
    { id: 3, name: "Charlie", species: "Velociraptor", sector: "B", health: 88, fed: false },
    { id: 4, name: "Trike", species: "Triceratops", sector: "C", health: 92, fed: true }
  ],

  getHealthReport: function() {
    console.log(`\nHEALTH REPORT - ${this.name}`);
    console.log("=".repeat(50));

    const avgHealth = this.dinosaurs
      .map(d => d.health)
      .reduce((sum, h) => sum + h, 0) / this.dinosaurs.length;

    console.log(`Average health: ${avgHealth.toFixed(1)}%`);

    const needsAttention = this.dinosaurs.filter(d => d.health < 90);

    if (needsAttention.length > 0) {
      console.log(`\nNeed attention (${needsAttention.length}):`);
      needsAttention.forEach(d => {
        console.log(`  - ${d.name}: ${d.health}% health`);
      });
    }

    return { avgHealth, needsAttention: needsAttention.length };
  },

  getFeedingStatus: function() {
    console.log(`\nFEEDING STATUS - ${this.name}`);
    console.log("=".repeat(50));

    const hungryDinos = this.dinosaurs
      .filter(d => !d.fed)
      .map(d => ({ name: d.name, sector: d.sector }))
      .sort((a, b) => a.sector.localeCompare(b.sector));

    if (hungryDinos.length > 0) {
      console.log(`Hungry dinosaurs (${hungryDinos.length}):`);
      hungryDinos.forEach(d => {
        console.log(`  Sector ${d.sector}: ${d.name}`);
      });
    } else {
      console.log("All dinosaurs fed!");
    }

    return hungryDinos;
  },

  getSectorReport: function() {
    console.log(`\nSECTOR REPORT - ${this.name}`);
    console.log("=".repeat(50));

    const sectors = this.dinosaurs.reduce((acc, dino) => {
      if (!acc[dino.sector]) {
        acc[dino.sector] = [];
      }
      acc[dino.sector].push(dino.name);
      return acc;
    }, {});

    Object.entries(sectors)
      .sort(([a], [b]) => a.localeCompare(b))
      .forEach(([sector, dinos]) => {
        console.log(`  Sector ${sector}: ${dinos.join(", ")}`);
      });

    return sectors;
  }
};

// Run all reports
parkSystem.getHealthReport();
parkSystem.getFeedingStatus();
parkSystem.getSectorReport();

console.log("\nCongratulations! You've mastered arrow functions!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Hands-on tasks in the game

  • Code editor

    You have the data: const ageYears = 25, const weightKg = 8000 and const heightM = 5.6. Calculate ageDays, the age in days (a year has 365 days), and bmi, the weight divided by the square of the height. Display ageDays and bmi rounded to two decimal places (toFixed(2)) in the console.

  • Horizontal ordering

    Arrange the elements of a correct let variable declaration with value assignment:

  • Code editor

    You have the data: const fenceVoltage = 10000, const requiredVoltage = 8000, const visitorsInPark = 250 and const maxVisitors = 500. Create Boolean variables: isFenceSecure (the voltage is equal to the required one or higher), isParkFull (the number of visitors has reached the limit) and canAcceptVisitors (the fence is secure and at the same time the park is not full). Display all three in the console.

  1. Coding taskNumber Operations
  2. Put in orderlet Variable Declaration Syntax
  3. Coding taskBoolean Logic

Useful articles