Functions are a way of hiding details about how something is done.
Hiding details is called abstraction.
Math
functions.
Math.sqrt
and Math.abs
are examples of
functions that are provided by Javascript that you’ve used.
You don’t have to know how to compute a square root to use
Math.sqrt
.
Those details are hidden, a.k.a. abstracted.
Now you are going to start writing your own functions.
const name = ...
const name = (arg1, arg2) ...
const name = (arg1, arg2) => {
// code goes here
};
The body can contain any code.
For functions that return values, it must contain a
return
statement.
A return
statement consists of the word
return
followed by an expression, whose value is
returned from the function to whatever code called it.
Here’s a function named add
that takes two arguments
and returns their sum:
const add = (a, b) => {
return a + b;
};
For simple functions, the whole function body may be just be a
return
statement.
A function to draw a triangle:
const drawTriangle = (x1, y1, x2, y2, x3, y3, color, width) => {
drawLine(x1, y1, x2, y2, color, width);
drawLine(x2, y2, x3, y3, color, width);
drawLine(x3, y3, x1, y1, color, width);
};
Note, no return
statement since this function doesn’t
return a value.
There’s another way of writing functions that some of you are familiar with already:
function add(a, b) {
return a + b;
}
This is an older style. It is not as bad as using
var
to define variables but modern Javascript style
prefers the syntax I gave earlier.
I’m going to ask you to use the modern style in this class.