Skip to content

Przemysław Konieczniak - Dev Notes

First Class Functions

Functional Programming, JavaScript

First Class Functions

If you are a JavaScript programmer this term should be quite familiar to you. Maybe you even don't know that in your daily work you are using with First Class Functions.

When the functions are treated like any other value in the programming language, that's mean that they are First Class Functions.

  • Functions can be stored in variables
    const log = console.log
    const add = (...args) => args.reduce((x, y) => x + y, 0)
  • Functions can be stored in arrays
    const queue =
    [
    () => console.log('foo'),
    () => console.log('bar'),
    () => console.log('baz')
    ]
    queue.shfit()()
  • Functions can be passed as arguments to the other functions and return them
    const onError = error => throw err
    const onSuccess = data => console.log(data)
    fs.readFile(onError, onSuccess)
  • Functions can be stored as a value of the object property
    const obj = {
    foo: function foo () { return 'foo' },
    bar: function () { return 'bar' },
    baz: () => 'baz'
    }
  • Functions can be created using constructor like other objects
    const fn = new Function('a', 'b', 'return a * b');
    fn(5, 6)
© 2020 by Przemysław Konieczniak - Dev Notes. All rights reserved.