a gentle introduction to functional programming in javascript
[WHAT]
- [] This is part one of a four-part series introducing ‘functional’ programming in JavaScript. In this article we take a look at the building blocks that make JavaScript a ‘functional’ language, and examine why that might be useful.
[WHY]
- []
[WHERE]
- [] READ THE FULL ARTICLE
- [] https://jrsinclair.com/articles/2016/gentle-introduction-to-functional-javascript-intro/
[WHEN]
- [] 2014-04-22 - original linked part 3 article @ different site
- [] 2019-11-23 - replaced original link with
[EXAMPLE]
- [] excerpt by smmry.com
In JavaScript we have two key building blocks: variables and functions.
Now, a function, on the other hand, is a way to bundle up some instructions so you can use them again, or just keep things organised so you're not trying to think about everything all at once.
Our log() function is a variable; which means that we can do the same things with it that we can do with other variables.
Could we, maybe, pass a function as a parameter to another function?
This ability to put functions into variables is sometimes described by saying "Functions are first class objects in JavaScript." What that means is just that functions aren't treated differently to other data types like objects or strings.
We want to initialise a carousel for the elements on the page, each one with a specific ID. So, let's describe how to initialise a carousel in a function, and then call that function for each ID. function initialiseCarousel(id, frequency) initialiseCarousel('main-carousel', 3000); initialiseCarousel('news-carousel', 5000); initialiseCarousel('events-carousel', 7000);.
We have a pattern to follow: when we have the same set of actions we want to take on different sets of data, we can wrap those actions up in a function.
There is definitely a repeated pattern, but we're calling a different function for each element.
Function addMagicClass(id) var unicornEl = addMagicClass('unicorn'); spin(unicornEl); var fairyEl = addMagicClass('fairy'); sparkle(fairyEl); var kittenEl = addMagicClass('kitten'); rainbow(kittenEl);.
The ability to pass functions around as variables opens up a lot of possibilities.
[HOW-TO]
- []
[REFERENCE]
- [] src = hn comments
By Tech.pro - Apply(), Call() and the arguments object