10.3.1. Function Examples

/*Let's see function syntax in action. We first consider a program that
prints an array of names.*/

let names = ["Lena", "James", "Julio"];

for (let i = 0; i < names.length; i++) {
   console.log(names[i]);
}

/*Following this pattern, we can create a function that prints any array
of names.*/

function printNames(names) {
   for (let i = 0; i < names.length; i++) {
      console.log(names[i]);


/*Breaking down the components of a function using our new terminology
gives us:  */

//Function name: printNames
//Parameter(s): names
//Body:
for (let i = 0; i < names.length; i++) {
   console.log(names[i]);
}
     
/*Notice that there is nothing about this function that forces names 
to actually contain names, or even strings. The function will work 
the same for any array it is given. Therefore, a better name for this
function would be printArray.

Our function can be used the same way as each of the built-in 
functions, such as console.log, by calling it. Remember that calling
a function triggers its actions to be carried out.*/
     
function printArray(names) {
   for (let i = 0; i < names.length; i++) {
      console.log(names[i]);
   }
}

printArray(["Lena", "James", "Julio"]);
console.log("---");
printArray(["orange", "apple", "pear"]);

//Lena
//James
//Julio
//---
//orange
//apple
//pear
     
     
/*This example illustrates how functions allow us to make our code 
abstract. Abstraction is the process of taking something specific
and making it more general. In this example, a loop that prints the
contents of a specific array variable (something specific) is 
transformed into a function that prints the contents of any array 
(something general).*/

0
6

                                    //To create a function, use the following syntax:

function myFunction(parameter1, parameter2,..., parameterN) {

   // function body

}

0
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source