-
Notifications
You must be signed in to change notification settings - Fork 9
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.
From the earliest versions of JavaScript you've had two way to write functions:
- Named functions
- Anonymous 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.
/** 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
class Math {
add(a, b) {
return a + b;
}
}
const math = new Math();
math.add(2, 3); // 5
const math = {
add(a, b) {
return a + b;
},
};
math.add(2, 3); // 5
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
// 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;
};
const foo = [1, 2, 3, 4];
const bar = foo.map((function () { return })
const math = {
add: function (a, b) {
return a + b;
}
}
math.add(2, 3); // 5