Back to Browse

Part 38 JavaScript Tutorial | Pure functions | Impure functions | global variables

100 views
Apr 5, 2023
5:01

A pure function is a function that always returns the same output given the same inputs and has no side effects on the program's state or external environment. In other words, a pure function: Does not modify or mutate its arguments Does not rely on or modify any external state or data Returns the same output for the same input, regardless of when or where it is called function addNumbers(a, b) { return a + b; } his function takes two arguments a and b, performs a simple addition operation on them, and returns the result. It does not modify its arguments or rely on any external state, and it always returns the same output for the same input. In contrast, here's an example of an impure function: let counter = 0; function incrementCounter() { counter++; return counter; } This function relies on external state (the counter variable) and modifies it every time it is called. It does not always return the same output for the same input, since the output depends on the current value of the counter variable. Therefore, it is considered an impure function.

Download

0 formats

No download links available.

Part 38 JavaScript Tutorial | Pure functions | Impure functions | global variables | NatokHD