There are two common ways to define a function in Javascript:
Also referred to as a function declaration, this is a classic syntax common to many languages. Function declarations load the function into memory during the Creation Phase (iow, the function definition is "hoisted").
function greet() {
console.log('Hi!');
}
In Javascript, functions are considered First-class (citizens) and are treated like any other value. A function expression returns the function as a value which can then be assigned to a variable using the assignment operator =
.
const greet = function() {
console.log('Hi!');
};
In June 2015, a new version of Javascript (ES6) was released and added a new "fat arrow" syntax for declaring functions. You will often see this syntax in documentation:
const greet = () => {
console.log('Hi!');
}
- Code inside a function does not execute at the time of declaration. You have to invoke a function later to run the code inside it.
- Defining Functions
- Invoking a function
- Parameters vs arguments
- Return values