To declare a function in JavaScript, use the function keyword, a function expression, or an arrow function.
To use the function keyword to declare a function, simply precede the function name with the word function, then append the function name with a set of parentheses followed by a set of braces.
function myFunc() {
// Code goes here...
}
To use a function expression, first declare a variable, and set this variable to the word function immediately followed by a set of parentheses and then a seperate set of braces.
const myFunc = function() {
// Code goes here...
}
To use an arrow function expression, first declare a variable and set this to a set of parentheses followed by a fat arrow and then a set of braces.
const myFunc = () => {
// Code goes here...
}
The parenthesis in each case should include any parameters of the function, and the code to be executed should be included between the set of braces.
An additional way to declare a function is to omit the function keyword from the first example and use the shorthand method definition. This way is necessary to declare functions within object literals and classes.