3 Core JavaScript concepts you should understand (functions)

Jasterix - Jan 9 '20 - - Dev Community

In JavaScript, functions are first class objects, meaning that they can access and be passed into function. But what does that really mean? How is a first class function different from a higher order function or a callback function?

These terms aren't mutually exclusive, but I think it's important to explore the nuances.

First class vs higher order vs callback

  1. First class: In JavaScript, functions are treated as first-class objects. I already discussed why functions are objects in this post. A first class object is one that is treated like a variable, meaning they can be:

    1. stored to a variable
    2. passed as an argument (as a callback)
    3. returned from a function
  2. Higher order function: This refers to a function that accepts a function as an argument or returns a function as its result

  3. Call back function: A callback function is one that gets passed as an argument to a function

Just remember:

  1. A higher order function can accept a callback function as an argument
  2. Both higher order and callback functions are first-class functions. This is because JavaScript treats functions as first class objects

Because these 3 terms are so intertwined, I've included the links below that discuss all three, instead of one post for each term:

  • Any difference between First Class Function and High Order Function link...
  • Functional JavaScript: What are higher-order functions, and why should anyone care? link...
  • Closures, first-class functions, and higher-order functions link...

let arr = [1,2,3,4,5]

const firstClass = (num) => {
  return num * num
}

const higherOrder = (array, callback) => {
  let newArray = []
  for(let i = 0; i < array.length; i++){
    newArray.push(callback(array[i]))
  }
  console.log(newArray)
}

higherOrder(arr, firstClass) // [ 1, 4, 9, 16, 25 ]
Enter fullscreen mode Exit fullscreen mode

Still confused? Leave a comment to let me know. I'm happy to explain further!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player