Good question!
Here are some of the ways you can declare a function (that can possibly be named doSomething
):
Normal function declaration (for the lack of a better world)
This can defined in any block in your code
function doSomething() {
}
Class method and Object shorthand syntax (ES6 only)
These can only be declared inside Class blocks and objects where the function
keyword isn't required
class MyClass {
doSomething() { // class method
}
}
// ES6
const myObject = {
foo: 1,
bar: 'baz',
doSomething() { // shorthand: key 'doSomething' whose value is a function
},
}
// ES5 (also ES6)
var myObject = {
foo: 1,
doSomething: function doSomething() {
},
}
Anonymous Functions (functions without a name)
// doesn't have a name but can be invoked using the variable name
const myFunction = function () {}
Callback functions (also can be anonymous)
fetch('/path/to/page').then(function () {
// do something
})
// same as above but with name
fetch('/path/to/page').then(function doSomething() {
// do something
})
Immediately-Invoked Functions (IIFE)
(function doSomething() {
// do something immediately
}())
I'm going to pause here to note that all of the above types of function declaration above have their own scope. Meaning, the this
keyword references the actual function, not its surrounding scope.
Arrow functions (lexically scoped)
Meaning that these functions keeps surrounding context when using the this
keyword.
const doSomething = () => {
// do something
}
const myObject = {
doSomething: () => {
// do something
}
}
fetch('/path/to/page').then(() => {
// do something
})
(() => {
// do something immediately
})()