DEV Community

Suhas Parameshwara
Suhas Parameshwara

Posted on

Angular - Pure vs Impure Pipe

Originally written in devsuhas.com

A pipe is used to transform values in an Angular template. To know more about pipes, you can visit this link. Basically there are two types of pipes in Angular. They are called Pure and Impure pipes.

In this blog, we’ll explore why do we need Angular pipes and also we’ll see some detailed differences between pure and impure pipes.

Why Angular Pipes?

Change Detection is one of the coolest features in Angular. But you know there are some flaws in it and some times these flaws will be easily implemented by developers. Let’s take some example,

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: '<div *ngIf="filterUsers">Steve is present</div>',
  styleUrls: [ './app.component.css' ]
})
export class MyComponent  {
  students = [{name: 'Steve', age: 22}, {name: 'Smith', age: 26}];

  get filterUsers(): boolean {
    console.log("I'm working")
    return !!this.students.filter(user => user.name == 'Steve').length;
  }
}

In the above example, we are calling a getter function from the respective template. As you see, we should be able to see the output and everything will be working fine. But when you notice the console, you would be seeing more logs than expected.

Alt Text

So this is not good because if we have any complex logic in that function, then it would impact the performance of our angular application. This happens mainly because,

How would change detection mechanism know if its return value has changed?

The problem is, it cannot detect. So how often these change detection occurs? It totally depends on the event in templates such as user input, setTimeout, observables etc. And as you see for every change detection in your template these function may be called. So that’s why we have pipes.

We should use pipes whenever we want to perform some logic on data inside our templates. And also these pipes can be created once and can be reused across your applications.

Before exploring pure and impure pipes, first let us try to understand pure and impure functions.

Pure vs Impure Functions

A function is called as pure function if,

  • It does not depend not any state, data or change during the program’s execution.
  • The function always returns the same result, if the same arguments passed into the respective function.
  • It does not produce any observable effects such as API calls, data mutation etc.
    A function is called as impure function if,

  • It totally depends on state, data or change during the program’s execution and also the function does not return the same value because it totally depends on the external variables.

  • It can also produce observable effects such as API calls, data mutation etc.
    Let’s take a simple function as example,

function calculatePrice(itemPrice){
    return totalPrice + itemPrice;
}

The above function is an example of pure function. If you pass the same argument 100 times, the output will be the same for this function. So it does not depend on state or data change.

Let’s see an another example,

var discount = 20; //This value may depend on the products purchased

function calculatePrice(itemPrice){
    return totalPrice + (itemPrice - discount);
}

The above function is an example of impure function. Can you guess why? Because the function return value depends on the external variable called discount. It may vary based upon the products.

So the take away from these examples are,

Pure:

  • If the input parameter is same, you will get the same output irrespective of the times it being called.
  • It can be shared across application without affecting the output result.

Impure

  • The output of the respective function cannot be predicted.
  • It cannot be shared across application because it may affect the internal logic.

Pure vs Impure Pipe

Now let us apply the same for pipes. The behavior of pure and impure pipe is same as that of pure and impure function. Let us try to solve the problem that we were facing in why angular pipes section.

Let us now create an pure pipe(By default all the pipes created in angular are pure pipe),

filter.pipe.ts

import {PipeTransform,Pipe} from '@angular/core'

@Pipe({
  name:'filter',
})
export class FilterPipe implements PipeTransform{


transform(value:any[]):any{
  console.log("I'm working");
  return !!value.filter(user => user.name == 'Steve').length;
 }
}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<div *ngIf="students | filter">Steve is present</div>',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  students = [{name: 'Steve', age: 22}, {name: 'Smith', age: 26}];
}

The above pipe will work fine and if you see the console, it will have only one log saying I’m working. But now let us turn these pipe into impure and let us see what’s gonna happen.

import {PipeTransform,Pipe} from '@angular/core'

@Pipe({
  name:'filter',
  pure: false
})
export class FilterPipe implements PipeTransform{


transform(value:any[]):any{
  console.log("I'm working");
  return !!value.filter(user => user.name == 'Steve').length;
 }
}

Now if you goto the console, you’ll be seeing multiple logs. So what’s the difference between creating a function and calling it in html vs impure pipe?

Basically a pipe can be created once and can be used across projects. But a function cannot be reused across projects. That’s the basic difference between them and otherwise the behavior is the same.

Conclusion

These are my explorations on Pure and Impure pipe. To know more about pipes you can visit this link.

I have also made a video on this topic in my YouTube channel. Take a look it at and show some love.

IMAGE ALT TEXT HERE

Top comments (0)