JavaScriptLesson 6 of 10Jump to practice
Functions
Package code you want to reuse into functions with parameters and return values.
A function is a named block of code you can run whenever you need it. Write it once, use it many times.
Declaring and calling
<script>
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Emma");
greet("Diego");
greet("Sofia");
</script>function greet(name)declares the function.nameis a parameter: a placeholder for a value.greet("Emma")calls it."Emma"is the argument that fills the placeholder.
Returning a value
return sends a result back to the code that called the function. The function stops there.
<script>
function withTax(price) {
return price + price * 0.08;
}
const total = withTax(1000);
console.log("$1000 plus 8% sales tax:", total);
console.log("Two items:", withTax(200) + withTax(300));
</script>Because withTax() returns a number, you can store it, add it up or pass it to another function.
Default values
Give a parameter a default, used when no argument is passed:
function greet(name = "friend") {
console.log("Hello, " + name);
}
greet(); // Hello, friend
greet("Emma"); // Hello, Emma
Arrow functions
A shorter way to write small functions. You’ll see them everywhere in modern code.
<script>
// These two do the same thing
function squareA(n) {
return n * n;
}
const squareB = (n) => n * n;
console.log(squareA(4), squareB(4));
// With more than one line, use braces and return
const describe = (name, age) => {
const label = age >= 18 ? "an adult" : "a child";
return name + " is " + label;
};
console.log(describe("Emma", 21));
</script>Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Declare a function called
greet.greet(name) { console.log("Hello, " + name); }Exercise 2Solved
Send the result back to whoever called the function.
function double(n) { n * 2; }Exercise 3Solved
Complete the arrow function.
const square = (n) n * n;An equals sign followed by a greater-than sign.
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.