Unary function in JavaScript

Pravin M
1 min readFeb 18, 2024
Unary function in JavaScript
Unary function in JavaScript

Source:- Unary function in JavaScript

For more questions and answers visit our website at Frontend Interview Questions

A unary function is a mathematical or programming function that takes exactly one argument. In programming, a unary function typically takes a single argument and produces a corresponding output.

Let’s explore a unary function with an example in JavaScript:

Example: Unary Function in JavaScript


// Unary function to square a number
function square(x) {
return x * x;
}

// Usage of the unary function
const number = 5;
const result = square(number);
console.log(result); // Output: 25

In this example, we have a unary function called `square` that takes a single argument `x`. The function calculates the square of the input number by multiplying `x` with itself and returns the result. When we call the function with `number` set to 5, it calculates the square (5 * 5) and returns 25, which is then printed to the console.

Conclusion:

As you can see, a unary function is a simple function that operates on a single argument, performing some computation, and returning the output. Unary functions are commonly used in various programming tasks, especially in functional programming paradigms, where operations on single values are frequent.

--

--

Pravin M
Pravin M

Written by Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com

No responses yet