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 variablesconst log = console.logconst add = (...args) => args.reduce((x, y) => x + y, 0)
- Functions can be stored in arraysconst queue =[() => console.log('foo'),() => console.log('bar'),() => console.log('baz')]queue.shfit()()
- Functions can be passed as arguments to the other functions and return themconst onError = error => throw errconst onSuccess = data => console.log(data)fs.readFile(onError, onSuccess)
- Functions can be stored as a value of the object propertyconst obj = {foo: function foo () { return 'foo' },bar: function () { return 'bar' },baz: () => 'baz'}
- Functions can be created using constructor like other objectsconst fn = new Function('a', 'b', 'return a * b');fn(5, 6)