DEV Community


Posted on • Updated on

3 Core JavaScript concepts you should understand (functions)

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++){

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!

Top comments (2)

mrksp profile image
Marcos S. • Edited

Hi ! Thanks for the post. I think you have a typo in the code snippet. In the last line where you console.log the higherOrder function, the callback argument is called square while the function that calculates the square is called firstClass :)

Also, I think the last line's console.log itself is not needed as you are already logging from inside the higherOrder function!

Edit: In the last console.log you're referencing 'arr' when the declared array is called 'array'.

jasterix profile image
Jasterix • Edited

Thanks for letting me know! I initially wrote the code with different variable names but thought it might be more helpful to use the concept names in place of the variables.

Also- great point about the extra console.log. As a new developer, constructive criticism is a huge help.

Just made the changes