Software Engineering :: Programming :: Languages :: JavaScript :: Functions
⪼ Made with 💜 by Polyglot.
- Personal Brand :: Social Media :: LinkedIn :: Post :: All the JavaScript function styles I know of
- Personal Brand :: Social Media :: LinkedIn :: Post :: All the JavaScript function styles I know of (Carousel)
Each function style has its own nuances, use cases, advantages, and limitations.
Which method to use depends on scope requirements, hoisting behavior desired, and whether the function is a method of an object or class.
Function declarations are one of the most common ways to define a function. They are hoisted, meaning they can be called before they are defined.
function add(a, b) {
return a + b;
}Function expressions are not hoisted, meaning they cannot be called before they are defined. A function expression can be named or anonymous.
A Named Function Expression (NFE) is a function where the function is given a name in addition to being assigned to a variable.
const add = function _add(a, b) {
return a + b;
};An anonymous function expression is a function without a name, defined inline and often used for short, one-off operations or passed as an argument to higher-order functions.
const add = function(a, b) {
return a + b;
};Arrow functions, introduced in ES6, offer a concise syntax for writing function expressions. They are anonymous and do not have their own
this,arguments,super,new.targetbindings, and NO.nameproperty.
const add = (a, b) => a + b;IIFEs are function expressions that are executed immediately after they are defined.
(function(a, b) {
console.log(a + b);
})(1, 2);((a, b) => console.log(a + b))(1, 2);Generator functions allow you to define an iterative algorithm by writing a single function whose execution is not continuous.
function* gen() {
yield 1;
yield 2;
yield 3;
}Async functions make it easier to work with asynchronous operations. They can be used with the
awaitkeyword.
async function request() {
return fetch('https://api.github.com/gists?per_page=100&page=1', {
method: 'GET',
headers: {
'Accept': 'application/vnd.github+json',
'Authorization': `Bearer ${process.env.GIST_API_KEY}`,
'X-GitHub-Api-Version': '2022-11-28'
}
})
.then(response => response.json())
.then(data => data && data.length && data[0].description ? data[0].description : '');
}Constructor functions are used to create objects. They are typically capitalized and used with the
newkeyword.
function MyConstructor() {
this.myProperty = 'value';
}
const myObject = new MyConstructor();ES6 introduced a shorthand syntax for defining methods within object literals.
const myObject = {
myMethod(a, b) {
return a + b;
}
};ES6 classes can also be used to define functions as methods of a class.
class MyClass {
myMethod(a, b) {
return a + b;
}
}