Passing functions as arguments: Array.forEach

by Ken Sprague

HTML

<h3>Functions as arguments</h3>
<div>
    <p>Functions are often passed as arguments to other functions. For an example of why we'd do this, look at the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach"><code>Array.forEach()</code> method</a>. </p>
    <p><code>Array.forEach()</code> accepts a function as its furst argument, and then executes that function once for each element of the array. </p>
    <p>This example will "fix" the capitalization of an array of strings so that only the first letter of each string is capitalized. </p>
    <p>Output will appear below:</p>
</div>
<div id="output"></div>

CSS

#output{
    width:80%;
    border: 1px solid black;
    padding: 1em;
}

JavaScript

var comicInfo = ["ASM", "129", "Graded" ];

comicInfo.forEach(function(title, issue, comicInfo){

	var title = title;
	var issue = issue;
	var correct = title + issue;
	//alert(correct);
	comicInfo[index] = correct;

});



logMessage(comicInfo);

// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id){
    if (!id){
        id="output";
    }
    document.getElementById(id).innerHTML += msg + "<br>";
}