JavaScript Functions and Arrow Functions
Introduction
Functions are the building blocks of JavaScript code. This tutorial covers the different ways to write them, including modern arrow functions, how to use default and rest parameters, and how functions power array methods like map and filter.
Prerequisites
- Basic JavaScript variables and data types
- A browser console or Node.js
Step-by-Step Guide
Step 1: Write a function declaration
A declaration starts with the function keyword and is available throughout its scope, even before the line where it's written.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5Step 2: Use function expressions and arrow functions
You can store a function in a variable. Arrow functions give a shorter syntax, and a single expression is returned automatically when you omit the braces.
const multiply = function (a, b) {
return a * b;
};
const square = (n) => n * n;
const greet = (name) => {
return "Hello, " + name;
};Step 3: Add default and rest parameters
Defaults supply a value when an argument is missing. The rest parameter (...) collects remaining arguments into an array.
function welcome(name = "friend") {
return "Welcome, " + name;
}
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(welcome()); // Welcome, friend
console.log(sum(1, 2, 3)); // 6Step 4: Pass functions as callbacks
Array methods such as map and filter take a function that runs on each item. Arrow functions keep these calls concise.
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter((n) => n % 2 === 0); // [2, 4]
const doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8, 10]FAQs
- What is the difference between arrow functions and regular functions?
- Arrow functions are shorter and don't have their own this. They use this from the surrounding scope, which is handy for callbacks but unsuitable for object methods that need their own this.
- What does a function return if there is no return statement?
- It returns undefined.
Summary
Use declarations for named, reusable functions and arrow functions for short callbacks. Default and rest parameters make your functions flexible without extra checks.
Comments
Log in or create a free account to join the discussion.