What is a function?
A function is a reusable block of code that performs a task. You define it once and call it many times.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Asha")); // Hello, Asha!nameis a parameter, and"Asha"is an argument.returnsends a value back to the caller.
Arrow functions
const add = (a, b) => a + b;
const square = n => n * n;
console.log(add(2, 3), square(4)); // 5 16Default and rest parameters
function welcome(name = "Guest") {
return `Welcome, ${name}`;
}
function total(...numbers) {
return numbers.reduce((sum, n) => sum + n, 0);
}
console.log(welcome(), total(1, 2, 3, 4));Scope
Variables declared inside a function are not visible outside it.
function test() {
const secret = 42;
}
// console.log(secret); // Error: secret is not definedlet and const are also block-scoped, which means they live inside the nearest { }.
Functions as values
<script>
function repeat(times, action) {
for (let i = 0; i < times; i++) action(i);
}
repeat(3, i => document.write("Run number " + (i + 1) + "<br>"));
</script>Functions can be passed to other functions. This idea, called a callback, is used everywhere in JavaScript.
Good practice
- Give functions clear verb names such as
calculateTotal. - Keep each function focused on one job.
- Avoid changing global variables inside functions.
Practice
Write a function isPrime(n) that returns true for prime numbers, and use it to print all primes up to 50.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Write a function that returns the larger of two numbers.
- Rewrite it as an arrow function.
- Add a default parameter and test it.
Common mistakes
- Forgetting return, so the result is undefined.
- Declaring variables inside a function and trying to use them outside it.
Quick check
What is the difference between a parameter and an argument?
A parameter is in the definition; an argument is the value passed when calling.
What does a function return without a return statement?
undefined.