Functions in JavaScript

Declarations, arrow functions, what this really means, and why callbacks are everywhere.

5 minute read · Free · Taught properly in our Front End Development Training in Amritsar

Three ways to write the same idea:

function add(a, b) { return a + b; }        // declaration
const add = function (a, b) { return a + b; };   // expression
const add = (a, b) => a + b;                // arrow

The arrow form is what modern code uses for short functions. With a single expression the return is implied.

const double = n => n * 2;
const greet = name => `Hello, ${name}`;
const nothing = () => {};

Functions are values

You can pass a function to another function. That is the whole basis of map, event handlers and every async API in the language:

button.addEventListener("click", () => {
  console.log("clicked");
});

setTimeout(() => console.log("one second later"), 1000);

A function passed like this is called a callback. Nothing special about it — it is just a value that happens to be runnable.

Default and rest parameters

function enrol(name, course = "Python") {
  return `${name}: ${course}`;
}

function total(...fees) {          // collects the rest into an array
  return fees.reduce((a, b) => a + b, 0);
}
total(4500, 4500, 4500);           // 13500

this, briefly

A normal function gets its own this, decided by how it was called. An arrow function does not — it uses the this from where it was written. That difference is why this breaks:

const timer = {
  count: 0,
  start() {
    setInterval(function () {
      this.count++;        // 'this' is not timer here
    }, 1000);
  },
};

and this works:

setInterval(() => { this.count++; }, 1000);

Rule of thumb until you know the details: use arrow functions for callbacks inside methods, and normal methods on objects and classes.

Hoisting

Function declarations can be called before the line that defines them. Arrow functions assigned to const cannot:

sayHi();                       // works
function sayHi() {}

sayBye();                      // ReferenceError
const sayBye = () => {};

Stuck on this in your own code?

That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some JavaScript, ask the mentor why yours is not working, and decide afterwards.