You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Functions are reusable blocks of code that perform a specific task. They are the primary way to organise and reuse code in JavaScript.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Bob")); // Hello, Bob!
The function keyword declares a function. Parameters are listed inside parentheses. The return statement sends a value back to the caller. If there is no return, the function returns undefined.
Functions can be assigned to variables:
const double = function(n) {
return n * 2;
};
console.log(double(5)); // 10
Arrow functions provide a shorter syntax, introduced in ES6:
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
// Multi-line arrow function
const multiply = (a, b) => {
const result = a * b;
return result;
};
// Single parameter — parentheses optional
const square = n => n * n;
// No parameters — empty parentheses required
const getRandom = () => Math.random();
When the body is a single expression, you can omit the curly braces and return keyword — the expression is returned implicitly.
Provide default values for parameters that might not be supplied:
function greet(name = "stranger") {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet()); // Hello, stranger!
Collect an arbitrary number of arguments into an array:
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
Variables declared inside a function are local to that function:
function calculate() {
const result = 42; // only accessible inside calculate
return result;
}
// console.log(result); // ReferenceError: result is not defined
Functions that accept other functions as arguments or return functions:
const numbers = [1, 2, 3, 4, 5];
// map — transform each element
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
// filter — keep elements that pass the test
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.