+6

What is the Immutability Pattern in JavaScript?

The immutability pattern is a way of designing code that relies on not changing the value of a piece of data once it has been created. This can be especially useful in functional programming, as it allows you to write code that is easier to reason about and debug.

Why Use the Immutability Pattern?

There are several benefits to using the immutability pattern in your code:

  1. It helps prevent accidental changes to data, which can lead to hard-to-track-down bugs.
  2. It allows you to write code that is easier to understand, as it clearly defines the input and output of each function.
  3. It can improve the performance of your code, as immutable data structures can be more efficiently implemented and optimized by JavaScript engines.

Example

Storing application state

In a large application, it can be useful to store the state of the app in a single, immutable object. This makes it easy to track changes to the state over time and debug any issues that may arise.

const initialState = {
  user: {
    name: 'John',
    age: 30
  },
  todos: []
}

function updateUser(state, user) {
  return {
    ...state,
    user
  }
}

const newState = updateUser(initialState, { name: 'Jane', age: 25 })
// newState: { user: { name: 'Jane', age: 25 }, todos: [] }

Managing a list of items

When working with lists of items, it can be useful to use immutable data structures to avoid accidental changes to the list.

const initialList = [1, 2, 3, 4]

function addItem(list, item) {
  return [...list, item]
}

const newList = addItem(initialList, 5)
// newList: [1, 2, 3, 4, 5]

Implementing undo/redo functionality:

The immutability pattern can be especially useful when implementing undo/redo functionality, as it allows you to easily track changes to data over time.

let currentState = {
  user: {
    name: 'John',
    age: 30
  }
}

const history = []

function updateUser(state, user) {
  history.push(state)
  return {
    ...state,
    user
  }
}

currentState = updateUser(currentState, { name: 'Jane', age: 25 })
// currentState: { user: { name: 'Jane', age: 25 } }

function undo() {
  currentState = history.pop()
}

undo()
// currentState: { user: { name: 'John', age: 30 } }

Validating user input

When validating user input, it can be useful to create a new, immutable version of the input data rather than changing the original data.

function validateInput(input) {
  const errors = []

  if (!input.name) {
    errors.push('Name is required')
  }
  if (!input.email) {
    errors.push('Email is required')
  }
  if (!input.password) {
    errors.push('Password is required')
  }

  return {
    ...input,
    errors
  }
}

const validatedInput = validateInput({ name: 'John', email: 'john@example.com' })
// validatedInput: { name: 'John', email: 'john@example.com', errors: ['Password is required'] }

Creating a report

When creating a report, it can be useful to create an immutable version of the data rather than modifying the original data.

const data = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Bob', age: 35 }
]

function createReport(data) {
  const report = {
    total: data.length,
    averageAge: data.reduce((sum, item) => sum + item.age, 0) / data.length
  }

  return {
    ...data,
    report
  }
}

const reportData = createReport(data)
  // reportData: [
  // { name: 'John', age: 30, report: { total: 3, averageAge: 30 } },
  // { name: 'Jane', age: 25, report: { total: 3, averageAge: 30 } },
  // { name: 'Bob', age: 35, report: { total: 3, averageAge: 30 } }
  // ]

Conclusion

The immutability pattern can be a useful tool for designing code that is easy to reason about and debug. By using this pattern, you can create code that is more predictable and easier to understand, which can ultimately lead to more maintainable and scalable applications.

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí