10.3.1. Function Syntax
//To create a function, use the following syntax:
function myFunction(parameter1, parameter2,..., parameterN) {
// function body
}
10.3.1. Function Syntax
//To create a function, use the following syntax:
function myFunction(parameter1, parameter2,..., parameterN) {
// function body
}
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).*/
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us