Running Functions
Defining a function does not run it. A function runs only when something calls it, and JavaScript offers several ways to do that. This page goes through them in turn.
Parentheses
Section titled “Parentheses”Writing the function’s name on its own refers to the function as a value. Adding parentheses after the name calls it:
function greet(name) { return `Hello, ${name}`;}
console.log(greet);console.log(greet('Maya'));This prints:
[Function: greet]Hello, MayaNode describes the function as [Function: greet], while a browser console shows its source. Either way, nothing inside greet() ran on the first line.
call(), apply() and bind()
Section titled “call(), apply() and bind()”Every function has call() and apply() methods, which run it with a chosen value for this. bind() does not run the function, but returns a copy with this fixed, which can be called later:
function label() { return `${this.name}: ${this.temp}°C`;}
const kitchen = { name: 'Kitchen', temp: 21 };
console.log(label.call(kitchen));console.log(label.apply(kitchen));
const kitchenLabel = label.bind(kitchen);console.log(kitchenLabel());This prints:
Kitchen: 21°CKitchen: 21°CKitchen: 21°CCall, Apply, and Bind Methods covers the differences between the three.
Passing it to another function
Section titled “Passing it to another function”A function can be passed to another function, which decides when to call it, and how often:
function twice(action) { action(); action();}
const beep = () => console.log('Beep');
twice(beep);This prints:
BeepBeepA function passed this way is a callback, which Callback Functions describes.
new, and methods
Section titled “new, and methods”Calling a function with new runs it as a constructor, which creates a new object and sets this to it. A function stored on an object, or on its prototype, runs as a method when it is called through the object:
function Room(name, temp) { this.name = name; this.temp = temp; this.warmer = function () { this.temp += 1; };}
Room.prototype.describe = function () { return `${this.name} is at ${this.temp}°C`;};
const hall = new Room('Hall', 17);hall.warmer();console.log(hall.describe());This prints:
Hall is at 18°Cwarmer() is a property of each room, while describe() lives once on Room.prototype and every room finds it through the prototype chain. A class does the same job with clearer syntax, and its methods go on the prototype automatically.
Reading a property
Section titled “Reading a property”A getter is a function that runs when a property is read, with no parentheses at all:
const thermostat = { readings: [18, 20, 22], get average() { console.log('Working out the average'); return this.readings.reduce((a, b) => a + b) / this.readings.length; },};
console.log(thermostat.average);This prints:
Working out the average20Getters and Setters covers these further.
Events
Section titled “Events”A function can wait for an event, and run each time the event happens. EventTarget is the interface that DOM elements use for this, and it is also available in Node, so any object built from it can send and receive events:
const sensor = new EventTarget();
sensor.addEventListener('reading', (event) => { console.log(`New reading: ${event.detail}°C`);});
console.log('Listening');setTimeout(() => { sensor.dispatchEvent(new CustomEvent('reading', { detail: 23 }));}, 20);This prints:
ListeningNew reading: 23°CThe listener runs only when dispatchEvent() sends a reading event, and CustomEvent carries data in its detail property. Node also has its own EventEmitter, which passes data straight to the listener as arguments:
const EventEmitter = require('node:events');
const sensor = new EventEmitter();sensor.on('reading', (temp) => console.log(`New reading: ${temp}°C`));sensor.emit('reading', 23);This prints:
New reading: 23°CSteve Griffith covers this topic in his video How to Make a Function Run.