Shared State in Javascript

Shared state can interact with just about anything; with side effects. The order of a function call matters which can also arise many bugs within your application.

So how can we write something that has no side effects? Something that won’t change whatever our array is you may ask?

We can copy the array inside our function!

Input/Function
Returned

Our global array and the newArray are exactly the same. We are using the concat() method instead of an = which would have given us the reference of the array(remember objects are passed by reference).

Instead of having them both point in the same direction, this way we have a unique copy of the array.

Then newArray.pop() and return newArray allows us to see the original array has not been changed.

Even though we created a new state inside the function, it is still a local variable. We are not changing or modifying anything outside of our scoped world. So because it has no affect on the outside world, we know what we can expect.

Input/Function
Returned

.map() returns a copy of the array

None of my arrays have changed. We have three distinct arrays. And all these functions have no side effects. They don’t affect anything that’s outside of their world.

None of the arrays have changed and we now have three unique arrays. Nor do any of these functions have side effects. Meaning they have no affect on anything outside of their scope.

But here is a distinct case:

Input/Function
Returned

This cannot be a pure function because console.log() uses the browser to log something to the said browser. Logging something outside its “world” hence modifying something outside of itself. Which is a perfect example of a side effect.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Quick Angular fix: the NgModule ‘AppModule’ needs to be compiled using the JIT compiler, but…

Steps to install an operator from command line in OpenShift

React: Rendering using Concurrent Mode and Suspense

HTB invite Challenge

VSCode Extension Filter Line

How to delete node_modules in the simplest way

How to remove node_modules

A Brief Introduction to React

Authentication using Phone Number

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Erick Villeda

Erick Villeda

More from Medium

Intro to Matter JS with React

React Project

What is React?

source(https://insights.stackoverflow.com/survey/2021#most-popular-technologies-webframe)