JavaScript Functions
A function is a block of code that runs when called. A function can take values in and send a value back.
Declare and call
A function runs when a call names it. This call runs greet twice with two different arguments.
function greet(name) {
console.log("Hello, " + name);
}
greet("Ana");
greet("Ben");Return a value
The return statement sends the doubled number back. The caller logs the value it receives.
function double(n) {
return n * 2;
}
console.log(double(6));A default value
The parameter name holds a default value here. A call with no argument uses that default.
function greet(name = "friend") {
console.log("Hello, " + name);
}
greet();
greet("Ana");Example
function greet(name = "friend") {
console.log("Hello, " + name);
}
function double(n) {
return n * 2;
}
function quiet() {
console.log("Inside quiet");
}
greet("Ana");
greet();
console.log(double(7));
console.log(quiet());Key points
- Parameter: the name in the function definition that receives a value
- Argument: the value passed in a call, such as "Ana" in greet("Ana")
- A return statement sends a value back to the caller.
- A default value fills a parameter when a call passes no argument.
- A function expression stores a function in a variable.
- A function without a return statement gives back undefined.
In this example, greet runs first with the argument "Ana" and logs a hello. The next call passes no argument, so the default "friend" fills the name. The double function returns 14, and the caller logs that value. The quiet function logs its line and returns nothing, so logging its call prints undefined.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a function do when it is called?