JavaScript/Reserved words/function
The function keyword
editThe function keyword stars the declaration and definition of a function. It can be used in two ways: either as
functionName = function(…) { […] };
or as
function functionName(…) { […] };
Examples
edit The code
capitalize = function(properName) {
return trim(makeProperName(properName));
};
function makeProperName(noun) {
if (typeof(noun) == 'string') {
if (noun.length > 1) {
chars = noun.split('');
for (i = 0; i < chars.length; i++) {
chars[i] = (i == 0 || chars[i - 1] == ' ')
? chars[i].toUpperCase()
: chars[i].toLowerCase();
}
noun = chars.join('');
}
}
return noun;
};
function trim(words, searchFor) {
if (typeof(words) == 'string') {
if (typeof(searchFor) == 'undefined') {
searchFor = ' '; // Two spaces
}
words = words.trim();
// As long as there are two spaces, do...
while ((index = words.indexOf(searchFor)) > -1) {
words = words.substring(0, index) + words.substring(index + 1);
}
}
return words;
};
var names = ['anton', 'andrew', 'chicago', 'new york'];
for (i = 0; i < names.length; i++) {
console.log("name = '" + capitalize(names[i]) + "'");
}
returns the following:
result = 3 name = 'Anton' name = 'Andrew' name = 'Chicago' name = 'New York'