Learn JavaScript · lesson 31 of 60 · about 8 minutes
Functions and Parameters
List every post on Sam's page with two reusable functions that take parameters and return text.
What you'll learn
- Declare a function
- Pass arguments to parameters
- Return values and use defaults
A line for every post
The page should list every post on its own line, like - My first loop (1 like), with the newest marked by a star instead of a dash. Writing that line out for each post would repeat the same code. A function writes it once: likeText(n) turns a number into 1 like or 4 likes, and postLine(post, marker) builds the whole line. The marker has a default, a dash, so only the newest needs to pass a star.
Reusable code
function name(params) { ... } defines a function. Calling name(args) runs it. return sends a value back and ends the function.
A function with no return gives back undefined.
Define and call
function area(width, height) {
return width * height;
}
const room = area(4, 3);
console.log(room);
console.log(area(2, 2) + area(1, 5));Output
12
9Default parameters
Give a parameter a default with =. It's used when the caller leaves that argument out.
Defaults
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet("Ada"));
console.log(greet("Bo", "Hey"));Output
Hello, Ada!
Hey, Bo!Tip
A function made with the function keyword can be called from anywhere in the file, even above where it's written. One function can call another: postLine calls likeText.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.