Brooks Patton
I have been working in the IT field for most of my professional career, first as a Systems Administrator at NASA Ames Research Center, as a software developer, and now I am an instructor at Galvanize.
with JavaScript
programming with functions, right?
The Object Oriented way
var evens = [];
function filterEvens(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 0) evens.push(arr[i]);
}
}
filterEvens([1, 2, 3, 4]);
var evens = [1, 2, 3, 4].filter(function(num){
return num % 2 === 0;
});
The Functional way
I have seen this on an interview!
Create a function that takes in an array and a callback function. For each item in the array the callback function will be executed with the following parameters
var arr = [1, 2, 3, 4];
function forEach(arr, cb){
// your code here
}
forEach(arr, function(num, i, arr){
console.log(num);
});
Another way to iterate over arrays!
var arr = [1, 2, 3, 4];
arr.forEach(function(item, i, arr){
console.log('item: ' + item);
console.log('i: ' + i);
console.log('arr: ' + arr);
});
I have also seen this on an interview!
Create a function that takes in an array and a callback function. For each item in the array the callback function will be executed with the returned value creating a new element in an array.
var arr = [1, 2, 3, 4];
function map(arr, cb){
// your code here
}
var newArray = map(arr, function(num, i, arr){
return num * 2;
});
console.log(newArray); // [2, 4, 6, 8]
A great way to manipulate arrays
var arr = ['bob', 'suzie', 'dave', 'lauren'];
var newArr = arr.map(function(item, i, arr){
return {name: item};
});
console.log(newArr);
Again, another interview question!
Create a function that takes in an array and a callback function. For each item in the array the callback function will be executed with the following parameters
var arr = [1, 2, 3, 4];
function filter(arr, cb){
// your code here
}
var newArr = filter(arr, function(num, i, arr){
return num % 2 === 0;
});
console.log(newArr); // [2, 4]
We don't like part of that array anyways!
var arr = [1, 2, 3, 4];
var newArr = arr.filter(function(item, i, arr){
return item % 2 === 0;
});
console.log(newArr);
By Brooks Patton
Introduction to functional programming using JavaScript.
I have been working in the IT field for most of my professional career, first as a Systems Administrator at NASA Ames Research Center, as a software developer, and now I am an instructor at Galvanize.