What is a Unary Function?
Unary functions are commonly used in programming to transform values. They take in a single input value and return a transformed value. Some common examples of unary functions include the
parseInt() function, which converts a string to an integer, and the
parseFloat() function, which converts a string to a floating-point number.
// Example 1 const double = x => x * 2; console.log(double(4)); // Output: 8 // Example 2 const square = x => x * x; console.log(square(5)); // Output: 25 // Example 3 const toLowerCase = str => str.toLowerCase(); console.log(toLowerCase("HELLO")); // Output: "hello"
In the first example, we define a
double function that takes in a number and returns the double of that number. In the second example, we define a
square function that takes in a number and returns the square of that number. In the third example, we define a
toLowerCase function that takes in a string and returns the lowercase version of that string.
Related Concepts or Methods
Currying is a technique used in functional programming where a function with multiple arguments is transformed into a sequence of functions that each take a single argument. This can be useful when working with unary functions since it allows you to create new functions by partially applying the original function.
// Example using currying const add = x => y => x + y; const add2 = add(2); console.log(add2(3)); // Output: 5
In the above example, we define an
add function that takes two arguments and returns their sum. We then use currying to create a new function
add2 that adds 2 to any number passed to it.
Higher-order functions are functions that take one or more functions as arguments or return a function as their result. They are commonly used in functional programming to create more complex functions from simpler ones.
// Example using higher-order functions const map = (arr, fn) => arr.map(fn); const double = x => x * 2; console.log(map([1, 2, 3], double)); // Output: [2, 4, 6]
In the above example, we define a
map function that takes an array and a function as arguments and returns a new array with the function applied to each element of the original array. We then define a
double function and use it with the
map function to create a new array with each element doubled.