Last active
December 26, 2015 23:59
-
-
Save hanbzu/7234458 to your computer and use it in GitHub Desktop.
JavaScript: Functional aspects of the language. Based on Christian Johansen's http://cjohansen.no/talks/2012/javazone/#/ talk.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A simple function | |
function add(a, b) { | |
console.log(a + b); | |
} | |
// A first class function | |
// It can be passed along as a variable | |
var add = function (a, b) { | |
console.log(a + b); | |
}; | |
// A pure function: | |
// No side effects | |
var add = function (a, b) { | |
return a + b; | |
}; | |
// Higher-order functions | |
// A function can create and return another function | |
function makeAdder(base) { | |
return function (num) { | |
return base + num; | |
}; | |
} | |
var add2 = makeAdder(2); | |
add2(3); // 5 | |
add2(7); // 9 | |
var el = document.getElementById("btn"); | |
el.addEventListener("click", function (event) { | |
// ... | |
}); | |
$("input[type=submit]").on("click", function (event) { | |
// ... | |
}); | |
// Loops, | |
// Why are we looping? | |
// Side-effects, transformation, filtering, combining, etc. | |
// Lets look at some alternatives | |
// Standard, focused on sequence | |
for (var i = 0, l = arr.length; i < l; ++i) { | |
console.log(arr[i]); | |
} | |
// WHY are we looping? Not HOW are we looping... | |
arr.forEach(function (item) { | |
console.log(item); | |
}); | |
// What about mapping? | |
// From here: | |
var names = []; | |
for (var i = 0, l = tweeps.length; i < l; ++i) { | |
names.push(tweeps[i].name); | |
} | |
// To here: | |
var names = tweeps.map(function (t) { return t.name; }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment