12. JavaScript Functions
What you will learn
- How to create and call a function
- Parameters, arguments, and return values
- Default parameters
- Arrow functions
What is a function?
A function is a named block of code you can run whenever you need it. Write it once, use it many times, and keep your program organised.
Declaring and calling
Example
<p id="demo"></p>
<script>
function sayHello() {
document.getElementById("demo").textContent = "Hello from a function!";
}
sayHello(); // call the function
</script>
Output (after the script runs)
Hello from a function!
Declaring a function does nothing by itself. The code inside runs only when you call it with parentheses.
Parameters and arguments
Parameters are the names in the declaration. Arguments are the actual values you pass in when calling.
Example
<p id="demo"></p>
<script>
function greet(name, city) {
return "Hello " + name + " from " + city + "!";
}
document.getElementById("demo").innerHTML =
greet("Sam", "Lahore") + "<br>" + greet("Ali", "Dubai");
</script>
Output (after the script runs)
Hello Sam from Lahore!
Hello Ali from Dubai!
Return values
return sends a value back to where the function was called and ends the function. A function with no return gives back undefined.
Example
<p id="demo"></p>
<script>
function add(a, b) {
return a + b;
}
const total = add(5, 7);
document.getElementById("demo").textContent = "5 + 7 = " + total;
</script>
Output (after the script runs)
5 + 7 = 12
Good functions do one job. A function that calculates a price should return it, and a separate piece of code should decide where to show it. That makes each part easy to test and reuse.
Default parameters
Give a parameter a fallback value for when the caller leaves it out.
Example
<p id="demo"></p>
<script>
function welcome(name = "friend") {
return "Welcome, " + name + "!";
}
document.getElementById("demo").innerHTML =
welcome("Sam") + "<br>" + welcome();
</script>
Output (after the script runs)
Welcome, Sam!
Welcome, friend!
Function expressions and arrow functions
A function can be stored in a variable. Arrow functions are a shorter way to write them.
Example
<p id="demo"></p>
<script>
// function expression
const double = function (n) {
return n * 2;
};
// arrow function
const triple = (n) => n * 3;
// arrow function with several lines
const describe = (n) => {
const isEven = n % 2 === 0;
return n + (isEven ? " is even" : " is odd");
};
document.getElementById("demo").innerHTML =
double(4) + "<br>" + triple(4) + "<br>" + describe(7);
</script>
Output (after the script runs)
8
12
7 is odd
With one expression, an arrow function can skip the braces and return. Arrow functions are very common as short callbacks, which you will meet with arrays and events.
Functions as callbacks
A function can be passed to another function. You already did this with addEventListener:
Example
<p id="demo">Click the button.</p>
<button id="btn" type="button">Count clicks</button>
<script>
let clicks = 0;
function countClick() {
clicks++;
document.getElementById("demo").textContent = "Clicks: " + clicks;
}
document.getElementById("btn").addEventListener("click", countClick);
</script>
Output (before clicking; run it in the editor)
Click the button.
Notice countClick has no parentheses here. We pass the function itself, and the browser calls it on each click. Writing countClick() would run it immediately instead.
Common mistakes
- Declaring a function but never calling it.
- Forgetting
returnand gettingundefined. - Writing
addEventListener("click", myFunction())with parentheses. - Putting code after
return. It never runs. - Making one huge function that does many unrelated jobs.
Exercise
Write a function rectangleArea(width, height) that returns the area. Show the result of rectangleArea(6, 4), which should be 24.
Show solution
<p id="demo"></p>
<script>
function rectangleArea(width, height) {
return width * height;
}
document.getElementById("demo").textContent =
"Area: " + rectangleArea(6, 4);
</script>
Knowledge check
1. What does a function return if it has no return statement?
undefined
2. What is the difference between a parameter and an argument?
A parameter is the name in the declaration. An argument is the value passed in when calling.
3. Which syntax is an arrow function?
(n) => n * 2
Summary
- Functions package code you can call again and again.
- Parameters take values in, and
returnsends a value out. - Arrow functions and callbacks are used everywhere in modern JavaScript.