📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Assignment Immutability
  • Value Immutability
  • Object.freeze
  • Copy, don't mutate
  • Immutable data structures
  1. Javascript
  2. Functional Light Javascript

Immutability

A misunderstanding about immutability is that it's about making sure things don't change. But you want things to change in an application. Otherwise, what's the point in building an application if everything is static? State change is necessary and important.

So what is immutability? It's more accurate to say it's about making sure things don't change unexpectedly. It's about ensuring that if we do change something, it's intentional and predictable.

In other words, how do we control mutation/change?

Assignment Immutability

Assignment immutability is the idea that if you assign a value to a variable or property, you are not able to reassign it.

A lot of functional programmers tout the const keyword as the way to implement assignment immutability.

This is problematic for 2 reasons:

  1. Functional programmers try to avoid assigning variables at all and prefer to just pass values into functions. So how much does assignment immutability really matter?

  2. Assignment immutability doesn't make data types like objects and arrays immutable. Those can still be mutated.

  3. Most const assignments occur in a lexical scope, so their immutability is only linked to a small block of code. That's not that helpful.

Value Immutability

99% of the problems with mutability can be solved with value immutability, not assignment immutability.

Take the following snippet of code:

const orderDetails = {
  orderId: 42,
  total: basePrice + shipping,
};

// This is mutation!
if (orderedItems.length > 0) {
  orderDetails.items = orderedItems;
}

processOrder(orderDetails);

There may be mutation happening in orderDetails. How can we be sure whatever happens in processOrder is predictable now?

Object.freeze

Most of the time when we want an immutable data structure, what we really want is a read-only data structure.

It turns out there's a built-in function called Object.freeze for just that purpose.

processOrder(Object.freeze(orderDetails));

Note: Object.freeze is shallow, so it only freezes the first level of properties.

Some use cases:

  • Establishing constant values like configurations

  • When you get back an API response

Copy, don't mutate

Even if some function calls pass Object.freeze, you can't be 100% sure every function call now and in the future will.

The solution is to make a copy of your data structure before mutating it.

function processOrder(order) {
  const processedOrder = { ...order };
  if (!('status' in order)) {
    processedOrder.status = 'complete';
  }
  saveToDatabase(processedOrder);
}

Immutable data structures

As stated before, immutability is about making mutation predictable and structured. It doesn't mean the data structure can't change.

So, what does such an immutable data structure look like?

What you want is an API that creates a layer of control over your data structure. So, instead of directly changing the data structure, you do it through the API.

Specifically, that API will change the data structure by creating a new data structure with your changes having been applied. You're changing a copy and replacing the original with it.

Note: Making a copy of your data structure every time there's a change can get expensive. A high-quality immutable data structure should handle those performance concerns for you.

Pro tip: Two great libraries for immutable data structures are Immutable.js and mori.

PreviousCompositionNextRecursion

Last updated 3 years ago