Snippet - Capitalizing Words - Functional vs. Non-Functional

5 years ago

Can you spot some differences between the non-functional and functional examples below?

  • Length - The non-functional example uses a whopping 19 lines as opposed to only a few lines using a functional approach. In face we could squeeze it down to 2 lines using concise body syntax. This fact alone increases the chance that you will have a bug.
  • Looping and concatenation - Again, here is an another example where things can fail since there is a ton more code involved.
  • Variables - Within the non-functional example, we declare a whopping 6 variables. Compare that to ZERO. Yet another potential place for failure.
  • Style - The non-functional example is more imperative and involves explicitly telling the computer what to do. The functional example is declarative, and tells the computer what the results should look like.

Remember: Under all the interesting patterns and terse syntax you'll see in most functional examples is really the mindset which is really the core of functional programming.

Non-Functional Approach

const capitalizeNonFunctional = word => {
    let capitalizedWord = ''
    for (let i = 0; i < word.length; i++) {
        let char = word[i]
        if (i === 0) {
            char = char.toUpperCase()
        capitalizedWord += char
    return capitalizedWord

const capitalizeWordsNonFunctional = words => {
    const wordsSplit = words.split(' ')
    let newWords = ''
    for (let i = 0; i < wordsSplit.length; i++) {
        newWords += capitalizeNonFunctional(wordsSplit[i]) + ' '
    return newWords.trim()

Functional Approach

const capitalizeFunctional = word => {
    return word[0].toUpperCase() + word.slice(1)
const capitalizeWordsFunctional = words => {
    return words.split(' ')
        .join(' ')

Consuming the Code

let message1 = 'this is sentence about nothing'
message1 = capitalizeWordsNonFunctional(message1)

let message2 = 'this is a another sentence about nothing'
message1 = capitalizeWordsFunctional(message2.slice())


This Is Sentence About Nothing

This Is A Another Sentence About Nothing  

Source Code
Discuss on Twitter