JavaScript Functions: Regular and Arrow Functions
function declaration, function expression, arrow functions, parameters, default parameters, return values, first-class functions
JavaScript Functions: Regular and Arrow Functions
Functions are reusable blocks of code that perform a specific task. They are one of the most powerful features in JavaScript. Functions let you write code once and use it many times, making programs shorter, cleaner, and easier to maintain.
Function Declaration
A function declaration defines a named function. It is hoisted, meaning you can call it before it is defined in the file.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alice')); // 'Hello, Alice!'Function Expression
A function expression stores an anonymous function in a variable. It is not hoisted.
const add = function(a, b) {
return a + b;
};
console.log(add(3, 4)); // 7Arrow Functions
Arrow functions introduced in ES6 provide a shorter syntax. When the function body is a single expression, you can omit the curly braces and the return keyword.
const multiply = (a, b) => a * b;
console.log(multiply(5, 6)); // 30
const square = n => n * n;
console.log(square(9)); // 81
const sayHello = () => 'Hello!';
console.log(sayHello()); // 'Hello!'Default Parameters
Default parameters provide fallback values when arguments are not passed.
function createUser(name, role = 'viewer') {
return { name, role };
}
console.log(createUser('Bob')); // { name: 'Bob', role: 'viewer' }
console.log(createUser('Alice', 'admin')); // { name: 'Alice', role: 'admin' }Functions as First-Class Values
In JavaScript, functions are first-class values. You can pass them as arguments to other functions, return them from functions, and assign them to variables. This is the foundation of many powerful patterns.
const numbers = [5, 2, 8, 1, 9];
const sorted = numbers.sort((a, b) => a - b);
console.log(sorted); // [1, 2, 5, 8, 9]
function applyOperation(a, b, operation) {
return operation(a, b);
}
console.log(applyOperation(10, 3, (x, y) => x - y)); // 7