Libraries, APIs and Documentation
Two calls, and who wrote them
let side = Math.sqrt(1225);
console.log(Math.max(side, 40));
This prints 40. The first line calls Math.sqrt and gets back 35. The second calls Math.max, which returns the larger, 40. We called two procedures and wrote neither. Both come with JavaScript, in a collection named Math, and were tested long before this program ran.
Where the code comes from
A program can reuse code from two kinds of source. An internal source is code already in the same program, such as a function defined higher up in the file. An external source is code from outside it: Math, JSON, and the packages other programmers publish. A real project loads a package with an import line; this course's editor has only what the language ships.Example: a program defines toMiles at the top and calls it lower down. That call reaches an internal source. Its call to Math.abs reaches an external one.
Why call a library
Math.sqrt gives a square root in one call. Writing our own root-finder means a loop of guesses, a stopping rule, and a test for negative inputs. Similarly, .sort() replaces a sort written by hand. Thus a library makes a complex program simpler to build. The hard procedure already exists, and thousands of programs ran it before ours did.The API: what each procedure promises
Note that a call can be spelled right, run with no error, and still be wrong. What decides whether a call is right is the API.| Procedure | Takes | Gives back | The part we cannot guess |
|---|---|---|---|
Math.floor(x) | one number | the largest whole number at or below x | Math.floor(-3.2) is -4 (not -3) |
Math.max(a, b, ...) | separate numbers, any count | the largest of them | handed one array, it gives NaN |
Math.random() | nothing | a decimal from 0 up to, but excluding, 1 | 0 can come back; 1 never does |
text.indexOf(piece) | the value to look for | the index where it first appears | -1 when absent (not undefined) |
Note that no amount of care about spelling reveals the last column. A program that hands Math.max an array runs, prints NaN, and never complains. Similarly, .sort() with no compare function orders numbers as text, so
[10, 9, 1].sort() gives [1, 10, 9]. Such a program is correct by spelling and wrong by API.The program below calls three library procedures from the table and prints what each one gives back. Run it, then change it and run it again:
• Change
depth to 4.6, and then to -4.1.• Add a fourth number, larger than 63, to the
Math.max call.• Change
letter to "e", and then to "z".let depth = -4.6;
console.log("Math.floor:", Math.floor(depth));
console.log("Math.max:", Math.max(14, 63, 29));
let word = "pepper";
let letter = "p";
console.log("indexOf:", word.indexOf(letter));
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.