Week 5 Video 3.4 Passing functions as arguments: Array.forEach

by Lucille Kenney

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 myArray = ["LArry", "john", "BILL" ];

myArray.forEach(function(val, index, theArray){

	var lower = val.toLowerCase();
	var upper = val.toUpperCase();
	var correct = upper.substr(0, 1) + lower.substr(1);
	//alert(correct);
	theArray[index] = correct;

});



logMessage(myArray);

// 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>";
}