State Management with Redux & MobX

Pure & Impure Functions

Steve Kinney

Steve Kinney

State Management with Redux & MobX

Check out a free preview of the full State Management with Redux & MobX course

The "Pure & Impure Functions" Lesson is part of the full, State Management with Redux & MobX course featured in this preview video. Here's what you'd learn in this lesson:

Steve explains the meaning of pure and impure functions in terms of a function's side effects, and relates this to the mutation of objects and arrays in JavaScript.


Transcript from the "Pure & Impure Functions" Lesson

>> Steve Kinney: We're gonna talk a little bit about some terminology, just to make sure we're all on the same page. Cuz if we get really deep into this and I'm talking about pure and impure functions, you're like, I don't know about this. Or what does it mean to not mutate state in a language where all of your basic data structures are mutable, [LAUGH] right?

And how do we do that, right? Cuz otherwise, to have some common language and some common terminology will probably go a long way for us. So we'll talk first about pure and impure functions. A pure function, I am a liberal arts major, but what I'm told is a pure function is the functions you see in math class, right?

Where things go in and things come out, right? And if the same two arguments go in, the same result comes out. Impure functions can mutate things, or change stuff, or have other side effects. Effectively, if you wanna be totally on the pure function, functional programming train, the second you throw a console log in there, it's technically an impure function, right?

Cuz there's another thing happening on top of two arguments coming in, or x number of arguments coming in and one leaving. So this is a pure function. It takes a and b and returns a + b. An impure function is one that just hopes that b is existing in the kind of closure scope or global scope, right?

That involves things outside of the function. That is enough to make something impure. As I mentioned before, a console log makes it impure, right? And also, and this is important because Redux only deals with pure functions. Doing a thing where you hit an API, add a callback to the event queue that eventually gets called is impure, right?

Mostly, mutating arrays and objects is also impure cuz we're changing stuff from the outside world. And this is tricky cuz as I mentioned before, all of our data structures in JavaScript are mutable, right? Except, I guess, strings.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now