Lesson 8 of 15
Arrow Functions
Arrow Functions
Arrow functions are a shorter syntax for writing functions:
// Traditional function
function double(n) {
return n * 2;
}
// Arrow function — same behavior, shorter syntax
const double = (n) => n * 2;
// Single parameter — parentheses optional
const double = n => n * 2;
// Multiple parameters — parentheses required
const add = (a, b) => a + b;
When the body is a single expression, the result is returned automatically. No return keyword needed.
Multi-line Arrow Functions
For more complex logic, use curly braces with an explicit return:
const factorial = (n) => {
let result = 1;
for (let i = 2; i <= n; i++) result *= i;
return result;
};
Arrow Functions as Arguments
Arrow functions shine when passed as arguments to other functions:
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(n => n * n);
console.log(squares); // [1, 4, 9, 16, 25]
Your Task
Write two arrow functions:
const double— takes a number, returns doubleconst square— takes a number, returns its square
Then print double(7) and square(6).
JavaScript loading...
Loading...
Click "Run" to execute your code.