Pure Functions Javascript - A Way to Avoid Side Effects in Javascript

preview_player
Показать описание
Learn what are side effects in Javascript and what are pure functions. It's important to write mostly pure functions and avoid side effects and mutations. This makes your code more stable and robust. You will see on the real example 2 rules of pure functions and why they are important.

FOLLOW ME

RECOMMENDED VIDEOS

MY COURSES
Рекомендации по теме
Комментарии
Автор

Great vid! However, there are some things that I would like to address. I'm sorry, but what you did with that function is a no go in most languages. By making functions that are supposed to be impure pure, you are violating lots of practices.

- One, allocating memory for an entirely new object, where state of one could just be altered. Be mindfull of your memory, and be mindfull of informing the user that you are copying stuff. Yea it's Javascript and that tends to happen less then one might think, but it's still something to keep in mind. This goes on to be supported by number two.

- A function that describes to alter state, is allowed to alter state. Your function is called addItem. It should not just return a new object. In this case you inform the user of this function that it alters the state of a variable, your array. If I expect that to happen and it doesn't, then we've got ourselves a big problem. Always inform the programmer when you are returning a new object instead of the passed one.

- And third, use constants and readonly variables that can't be altered in any way shape or form. Don't expose functions publicly, that can directly or at all alter state. For an array, you can make it immutable whenever you pass it.

Great vid tho, good solid basis. Just don't forget to mention that one can write a pure function more easily if they use immutable parameters, and keep an eye on the function context.

LordErnie
Автор

Спасибо, освежил в памяти. Как насчет понятия детерминированности функции? Тоже ведь из этой оперы.

ilyaredkin
Автор

hi there, in your last example, cart.items is not an argument, even though cart is an argument, that is why it is not pure?

JJ-otps
Автор

Super, I would like to know what are the benefits can I get if I joined (membership)

anurap.kasthoori