1//To create a function, use the following syntax:
2
3function myFunction(parameter1, parameter2,..., parameterN) {
4
5 // function body
6
7}
8
1/*Let's see function syntax in action. We first consider a program that
2prints an array of names.*/
3
4let names = ["Lena", "James", "Julio"];
5
6for (let i = 0; i < names.length; i++) {
7 console.log(names[i]);
8}
9
10/*Following this pattern, we can create a function that prints any array
11of names.*/
12
13function printNames(names) {
14 for (let i = 0; i < names.length; i++) {
15 console.log(names[i]);
16
17
18/*Breaking down the components of a function using our new terminology
19gives us: */
20
21//Function name: printNames
22//Parameter(s): names
23//Body:
24for (let i = 0; i < names.length; i++) {
25 console.log(names[i]);
26}
27
28/*Notice that there is nothing about this function that forces names
29to actually contain names, or even strings. The function will work
30the same for any array it is given. Therefore, a better name for this
31function would be printArray.
32
33Our function can be used the same way as each of the built-in
34functions, such as console.log, by calling it. Remember that calling
35a function triggers its actions to be carried out.*/
36
37function printArray(names) {
38 for (let i = 0; i < names.length; i++) {
39 console.log(names[i]);
40 }
41}
42
43printArray(["Lena", "James", "Julio"]);
44console.log("---");
45printArray(["orange", "apple", "pear"]);
46
47//Lena
48//James
49//Julio
50//---
51//orange
52//apple
53//pear
54
55
56/*This example illustrates how functions allow us to make our code
57abstract. Abstraction is the process of taking something specific
58and making it more general. In this example, a loop that prints the
59contents of a specific array variable (something specific) is
60transformed into a function that prints the contents of any array
61(something general).*/