Modern Functions in JavaScript
Functions are reusable blocks of code designed to perform a particular task. They are executed when something "invokes" (calls) them.
In modern JavaScript, there are two main ways to declare functions: Traditional Functions and Arrow Functions.
Traditional Functions
They are declared using the function keyword, followed by a name, parentheses () that can contain parameters, and curly braces {} enclosing the code to be executed.
// Declaration
function greet(firstName, lastName) {
return `Hello, ${firstName} ${lastName}!`;
}
// Invocation (call)
const message = greet("John", "Doe");
console.log(message); // "Hello, John Doe!"
Anonymous Functions
In JS, functions are "first-class citizens", which means they can be treated like any other variable. You can assign an unnamed (anonymous) function to a const variable.
const add = function(a, b) {
return a + b;
};
console.log(add(5, 10)); // 15
Arrow Functions
Introduced in ES6, "Arrow Functions" provide a much shorter and concise syntax for writing functions, and they also change the way the this context behaves (a vital advanced topic in frameworks like React).
Basic syntax:
(parameter1, parameter2) => { code }
// Arrow Function equivalent to 'add' above
const addArrow = (a, b) => {
return a + b;
};
The superpower of conciseness (Implicit return)
If your arrow function only consists of a single line of code that returns a value, you can omit the curly braces {} and the word return. The return becomes implicit.
Furthermore, if the function receives exactly one parameter, you can omit the parentheses ().
// 1. Original syntax
const multiplyByTwo = (number) => {
return number * 2;
};
// 2. Omitting parentheses (only 1 parameter)
const multiplyByTwo = number => {
return number * 2;
};
// 3. IMPLICIT return (Only 1 line of code)
const multiplyByTwo = number => number * 2;
console.log(multiplyByTwo(5)); // 10
This ultra-short syntax (number 3) is what you will see in 90% of modern JavaScript code when using array methods (like .map or .filter).