Skip to content

Functions in JavaScript

Ole Anders Stokker edited this page Apr 11, 2019 · 1 revision

The JavaScript language develops quite fast. Since 2015 features have been added once a year through the ECMA standard.

function theGoodOldWay() { };

From the earliest versions of JavaScript you've had two way to write functions:

  • Named functions
  • Anonymous functions

Named functions

Named functions may be the easiest form of functions in the language. They work much the same as functions in other scripting languages, like Python.

Both of these types work very similarly.... // TODO: write more in detail or link to better resource.

Very basic example of a names function
/** Named function for adding two numbers together */
function add(a, b) {
	return a + b;
}

// same but with TypeScript
function add(a: number, b: number): number {
	return a + b;
}

add(2, 3); // 5
The same named function in a class
class Math {
	add(a, b) {
		return a + b;
    }
}

const math = new Math();
math.add(2, 3); // 5
Named function in an object literal
const math = {
	add(a, b) {
		return a + b;
	},
};

math.add(2, 3); // 5 

Anonymous functions

Named function always give the function a name, but what if you don't need a name. Anonymous functions can for example be used for callbacks // TODO: write about callbacks

anonymous function assigned to a variable/constant
// Same example as with named function, but with anonymous
const add = function(a, b) {
	return a + b;
};

// Same but with TypeScript
const add = function(a: number, b: number): number {
	return a + b;
};
anonymous function as a callback

const foo = [1, 2, 3, 4];

const bar = foo.map((function () { return })

anonymous function in a an object literal
const math = {
	add: function (a, b) {
		return a + b;
	}
}

math.add(2, 3); // 5

(arrowFunctions) => The new way