Quasilinear Thoughts

- A developer's log book.

Published on

# Higher order functions in Javascript

Authors
•  Name
Khalil
@Im_Khalil

A function that accepts and/or returns another function is called a higher-order function.

It’s higher-order because instead of strings, numbers, or booleans, it goes higher to operate on functions.

With functions in JavaScript, you can

• Store them as variables
• Use them in arrays
• Assign them as object properties (methods)
• Pass them as arguments
• Return them from other functions

## Example:

### Strings as arguments:

      sayHi = (name) => Hi, \${name}!;
result = sayHi('Khalil');
console.log(result); // 'Hi, Khalil!


### Numbers as arguments:

      double = (x) => x * 2;
result = double(4);
console.log(result); // 8


### Booleans as arguments:

      getClearance = (allowed) => allowed ?
result1 = getClearance(true);
result2 = getClearance(false);
console.log(result1); // 'Access granted'


### Objects as arguments:

      getFirstName = (obj)  => obj.firstName;
result = getFirstName({
firstName: 'Khalil'
});
console.log(result); // 'Khalil'


### Arrays as arguments:

     len = (array) => array.length;
result = len([1, 2, 3]);
console.log(result); // 3


### Functions as Arguments:

     isEven = (num) => num % 2 === 0;
result = [1, 2, 3, 4].filter(isEven);
console.log(result); // [2, 4]


### Returning Functions::

    add = (x) => (y) => x + y;  