JavaScript · Lesson 11 / 32 · English
JavaScript Functions
Understand the idea. Change the code. Build confidence with one focused experiment.
Read this lesson in தமிழ் ↗.
Start with the idea
A function packages reusable work. Parameters receive inputs and return sends a result to the caller. Logging a value and returning it are different operations.
Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.
Step-by-step lesson notes
Functions in JavaScript
Functions are reusable blocks of code designed to perform a particular task. JavaScript supports multiple function syntaxes and powerful features like closures and higher-order functions.
Function Declaration vs Expression
// Function Declaration — hoisted, can be called before definition
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // "Hello, Alice!"
// Function Expression — not hoisted
const greet2 = function(name) {
return `Hi, ${name}!`;
};
// Arrow Function (ES6) — concise syntax
const greet3 = (name) => `Hey, ${name}!`;
const double = n => n * 2; // single param, no parens needed
const add = (a, b) => a + b; // implicit returnParameters & Default Values
// Default parameters (ES6)
function createUser(name, role = "viewer", active = true) {
return { name, role, active };
}
console.log(createUser("Bob")); // { name: 'Bob', role: 'viewer', active: true }
console.log(createUser("Alice", "admin")); // { name: 'Alice', role: 'admin', active: true }
// Rest parameters — collect remaining args into an array
function sum(...numbers) {
return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15Closures
A closure is a function that remembers its outer scope even after that scope has finished executing.
function createCounter() {
let count = 0; // private variable
return {
increment: () => ++count,
decrement: () => --count,
value: () => count
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.decrement()); // 1
console.log(counter.value()); // 1Higher-Order Functions
// Functions that take other functions as arguments
const numbers = [1, 2, 3, 4, 5];
// map — transform each element
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter — keep elements that pass the test
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// reduce — accumulate into a single value
const total = numbers.reduce((acc, n) => acc + n, 0);
console.log(total); // 15Arrow functions don't have their own this — they inherit this from the enclosing scope. This makes them ideal for callbacks but not for object methods.
A complete example
Run this complete index.js program in the JavaScript console editor below. The earlier reference fragments may need a browser page or other surrounding setup.
function total(price, quantity) {
return price * quantity;
}
const bill = total(80, 3);
console.log(bill);Predict first. Reveal the expected result.
240
Make one change. See what happens.
Load the example, change a value, predict the output, and run it again. Use the console output to check your reasoning.
Wait for the editor to load, then load this example and press Run.
Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.
Put the idea to work
Practice challenge
Call total with 50 and 4, then add delivery of 30 outside the function.
Reveal the answer and reasoning
total(50, 4) + 30 is 230. The function remains focused on the subtotal.
One mistake to avoid: Without a return statement, a normal function returns undefined even if it logs a value.
Your learning checkpoint
- Explain the example in your own words.
- Complete the challenge before revealing its answer.
- Describe the common mistake and how to avoid it.