Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Unary Operators
2.1.
Unary plus (+)
2.2.
Unary minus (-)
2.3.
Increment (++)
2.4.
Decrement (--)
2.5.
Logical NOT (!)
3.
Pure Functions
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Unary Functions and Pure Function

Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

This article will cover the use of two topics in JavaScript, i.e., Unary Operators and Pure functions. Both have different individuality in terms of providing easiness in the code.

Also Read, Javascript hasOwnProperty

Unary Operators

You might have listened in other languages regarding the unary operators, which means operation on a single operand.

Let's go through some of these operators.

 

Unary plus (+)

The unary plus operator is a simple plus sign (+). If you place the unary plus(+) before a numeric value, let's see what it does through the example below.

For example

let x = 65;
let y = +x;

console.log(y); 

 

Output:

65

 

let fl = false,
    tl = true;

console.log(+tl); 
console.log(+fl); 

 

Output:

1
0

 

Suppose you have an object with the toString() method as follows:

 

let boy = {
  name: 'Harry',
  toString: function () {
    return '30';
  },
};

console. log(+boy);

 

Output:

30

 

After experimenting with different values in the above examples, you can continue to the next unary operator.

 

Unary minus (-)

The unary minus operator is denoted by a single minus sign (-). If you apply the unary minus operator to a numeric value, it negates the number. 

For example:

let x = 5;
let y = -x;

console.log(y);

 

Output

-5

 Suppose you apply the unary minus operator(-) to a non-numeric value. It converts the value into a number applying the same rules as the unary plus operator and then negates the value.

 

Increment (++)

The increment operator (++) increments its operand and returns the incremented value.

It can be used as a prefix operator or postfix operator.

  • Postfix: It means that the operator comes after the operand like this (y++). This returns the value before incrementing.
  • Prefix: The operator comes before the operand like this (++y). While using it as a prefix returns the value after incrementing.

 

Example of the postfix operator:

x = 6 // x = 6

y = x++ // y = 6 and x = 7

 

Here is a prefix example:

IIx = 4 // x = 4

y = ++x // y = 5 and x = 5

 

After experimenting with different values in the above example, you can continue to the next unary operator.

 

Decrement (--)

The decrement operator (--) decrements its operand and returns a value.

It can be used as a prefix operator or postfix operator.

  • Postfix means that the operator comes after the operand (y--). This returns the value before decrementing.
  • Prefix means that the operator comes before the operand (--y). while using it as a prefix returns the value after decrementing.

 

Here is a postfix example:

x = 6 // x = 6

y = x-- // y = 6 and x = 5

 

Here is a prefix example:

x = 4 // x = 4

y = --x // y = 3 and x = 3

 

After experimenting with different values in the above example, continue to the next unary operator.

 

Logical NOT (!)

The logical NOT (!) operator performs negation on the given expression; It takes truth to falsity and vice versa.

 

These examples below demonstrate how logical NOT returns false if the operand can be converted to true. If not, it returns false.

 

You can also use double negation (!!).

 

!!1 === true // returns true

!!0 === false // returns true

 

Let's examine the last example.

First, a negation of a string('0') returns false:

 

Then, a negation of false, returns true:

!false // returns true

Thus:

true === true // returns true

 

After experimenting with different values in the above examples, you can continue to the next unary operator.

 

Here is an image that depicts the order of precedence in operations when using Javascript.

 

 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Pure Functions

Pure functions are the building blocks in functional programming that always return the same result if the same arguments are passed. It does not depend on data change or any state during a program's execution; rather, it only depends on its input arguments.

 

A pure function will have the following properties:

  • It doesn't produce any side effects.
  • It will not change variables out of its scope.
  • It depends only on its arguments.

 

So, `console.log( double(5) );` is the same as `console.log(10);

 

This is true because `double()` is a pure function, but if `double()` had side effects, such as saving the value to the disk or logging into the console, you couldn't simply replace `double(5)` with 10 without changing the meaning.

 

Pic by Sarav. co

 

The Checklist

A function must pass two criteria to be considered "pure":

  • Same inputs always return the same outputs
  • No side-effects

Let's check in on each one.

 

Compare this:

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

add(4, 4); // 8

 

To this:

let x = 4;

const add = (y) => {
  x += y;
};

add(4); // x === 8 (the first time)

 

The first example returns a value based on the given parameters, regardless of when/where you call it.

If you pass 4 and 4, you'll always get 8.

Nothing else affects the output.

 

The second example returns nothing. It relies on a shared state to do its job by incrementing a variable outside its scope.

This pattern is a developer's nightmare fuel.

A shared state introduces a time dependency. You will get different results depending on when you call the function. The first time results in 8, and the next time is 12, and so on.

 

Example

 

<html>
<body>
<script>
   let val1 = 6;
   let val2 = 4;
   function pure() {
      return val1 * val2;
   }
   document.write(pure());
</script>
</body>
</html>

 

output

24

 

In the following example, the function depends on some outside variables(Val), even though depending on its arguments. So it is not a pure function. 

 

Note: If a pure function calls a pure function, this isn't a side effect, and the calling function is still considered pure. (Example: using Math.max() inside a function)

 

Below are some side effects (but not limited to) which a function should not produce to be considered a pure function –

 

  • Making an HTTP request
  • Mutating data
  • Printing to a screen or console
  • DOM Query/Manipulation
  • Math. random()
  • Getting the current time

You can try it by yourself on an online JS editor.

Frequently Asked Questions

1. What do you mean by Functional Programming in JavaScript?

Functional Programming in JavaScript teaches JavaScript developers functional techniques to improve extensibility, modularity, reusability, testability, and performance.

 

2. What are the types of unary operators in JavaScript?

Unary plus(+)

Unary minus(-)

Increment(++)

Decrement(--)

Logical Not(!)

Bitwise Not(~) 

 

3. What do you mean by Pure Functions in JavaScript?

A pure function is a deterministic function. When the same input is passed every time, the function will return the same output.

 

Conclusion

After this long detailed article, let's summarize some points for better clearance of the topics. Here we have discussed the unary operators and pure functions in JavaScript.

 

Unary operators work on one value. One thing that one should ponder is that one should always consider the order of operations when dealing with more than one operator.

A function's pure if it's free from side effects and returns the same output for the same input. Side-effects include: mutating input, printing to the screen, HTTP calls, and writing to disk. 

 

If you'd like to learn more about JavaScript, check out the free content of JavaScript for exercises and programming projects.

 

Happy Coding!!!

 

 

Live masterclass