A named group of statements.
Functions help with organizing and reusing code. For example, functions make it easy to express the idea "Draw a flower.":
function drawFlower() {
// Style the text.
textAlign(CENTER, CENTER);
textSize(20);
// Draw a flower emoji.
text('🌸', 50, 50);
}
The function header begins with the keyword function
. The function's name, drawFlower
, is followed by parentheses ()
and curly braces {}
. The code between the curly braces is called the function's body. The function's body runs when the function is called like so:
drawFlower();
Functions can accept inputs by adding parameters to their headers. Parameters are placeholders for values that will be provided when the function is called. For example, the drawFlower()
function could include a parameter for the flower's size:
function drawFlower(size) {
// Style the text.
textAlign(CENTER, CENTER);
// Use the size parameter.
textSize(size);
// Draw a flower emoji.
text('🌸', 50, 50);
}
Parameters are part of the function's declaration. Arguments are provided by the code that calls a function. When a function is called, arguments are assigned to parameters:
// The argument 20 is assigned to the parameter size.
drawFlower(20);
Functions can have multiple parameters separated by commas. Parameters can have any type. For example, the drawFlower()
function could accept Number
parameters for the flower's x- and y-coordinates along with its size:
function drawFlower(x, y, size) {
// Style the text.
textAlign(CENTER, CENTER);
// Use the size parameter.
textSize(size);
// Draw a flower emoji.
// Use the x and y parameters.
text('🌸', x, y);
}
Functions can also produce outputs by adding a return
statement:
function double(x) {
let answer = 2 * x;
return answer;
}
The expression following return
can produce an output that's used elsewhere. For example, the output of the double()
function can be assigned to a variable:
let six = double(3);
text(`3 x 2 = ${six}`, 50, 50);
Examples
Related References
stringify
From the MDN entry: The JSON.stringify() method converts a JavaScript object or value to a JSON string.
log
Prints a message to your browser's web console.
===
The strict equality operator === checks to see if two values are equal and of the same type.
Array
A list that keeps several pieces of data in order.