Return to site

ANGULAR INTERVIEW QUESTION: What is the difference between pure and impure pipes?

January 29, 2022

ðŸ’Ą 𝐏𝐔𝐑𝐄 𝐏𝐈𝐏𝐄𝐒

Pure pipes are stateless, which means that there is no handling of a state between two calls, and there's no collateral effect.

Hence, a pure pipe is called only when Angular detects a change in the value parsed to the pipe.

uppercase.pipe.ts

<ℎ1>{{ ð‘Ąð‘–ð‘Ąð‘™ð‘’ | ð‘Ē𝑝𝑝𝑒𝑟𝑐𝑎𝑠𝑒 }}

ðŸ’Ą 𝐈𝐌𝐏𝐔𝐑𝐄 𝐏𝐈𝐏𝐄𝐒

On the other hand, Angular calls an impure pipe for each change detection cycle, no matter the value could change.

This can be useful in some cases when usual pipe changes can't be detected by Angular:

👉 When we parse to the pipe an array or an object whom content did not change, while the instance is still the same.

👉 When your pipe injects a service to access other values, but Angular has no way to detect the changes and does not update the view.

In such cases, using an impure pipe is meaningful, because your pipe is executed and your display updated.

But remember that impure pipes may be less efficient.

For example, when an array is parsed to an impure pipe to filter or sort the data, then the processing could be executed each time the change detection runs, even if the array did not change.

In that case, your pipe should try to detect this and send data from a cache.

𝑚𝒐 𝒂 𝒑𝒖𝒓𝒆 𝒑𝒊𝒑𝒆 𝒊𝒔 𝒄𝒂𝒍𝒍𝒆𝒅 𝒐𝒏𝒍𝒚 𝒘𝒉𝒆𝒏 ð‘Ļ𝒏𝒈𝒖𝒍𝒂𝒓 𝒅𝒆𝒕𝒆𝒄𝒕𝒔 𝒂 𝒄𝒉𝒂𝒏𝒈𝒆 𝒊𝒏 𝒕𝒉𝒆 𝒗𝒂𝒍𝒖𝒆 𝒑𝒂𝒓𝒔𝒆𝒅 𝒕𝒐 𝒕𝒉𝒆 𝒑𝒊𝒑𝒆.

ð‘Ļ𝒏 𝒊𝒎𝒑𝒖𝒓𝒆 𝒑𝒊𝒑𝒆 𝒊𝒔 𝒄𝒂𝒍𝒍𝒆𝒅 𝒇𝒐𝒓 𝒆𝒂𝒄𝒉 𝒄𝒉𝒂𝒏𝒈𝒆 𝒅𝒆𝒕𝒆𝒄𝒕𝒊𝒐𝒏 𝒄𝒚𝒄𝒍𝒆, 𝒘𝒉𝒂𝒕𝒆𝒗𝒆𝒓 𝒕𝒉𝒆 𝒗𝒂𝒍𝒖𝒆 𝒄𝒉𝒂𝒏𝒈𝒆𝒔. ð‘Ū𝒆𝒏𝒆𝒓𝒂𝒍𝒍𝒚, 𝒘𝒆 𝒂𝒗𝒐𝒊𝒅 𝒖𝒔𝒊𝒏𝒈 𝒊𝒎𝒑𝒖𝒓𝒆 𝒑𝒊𝒑𝒆𝒔 𝒃𝒆𝒄𝒂𝒖𝒔𝒆 𝒐𝒇 𝒕𝒉𝒆𝒊𝒓 𝒄𝒉𝒆𝒂𝒑 𝒆𝒇𝒇𝒊𝒄𝒊𝒆𝒏𝒄𝒚.