<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>
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>";
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.