JavaScript Functions & Arrow Functions
Learn how to write modular code using traditional functions and the modern, concise ES6 Arrow Function syntax.
Function Declarations
A JavaScript function is a block of code designed to perform a particular task. A function is executed when "something" invokes it (calls it).
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 3); // result is 12Function Expressions
A function can also be defined using an expression. Function expressions can be stored in a variable.
const add = function(a, b) {
return a + b;
};ES6 Arrow Functions
Arrow functions were introduced in ES6. They allow us to write shorter function syntax. They do not bind their own this, which makes them perfect for callbacks inside classes or object methods.
// Traditional
const divide = function(a, b) {
return a / b;
}
// Arrow Function
const divideArrow = (a, b) => a / b;If the arrow function has only one parameter, you can omit the parentheses around the parameter.