- vừa được xem lúc

Blog#81: What is the Immutability Pattern in JavaScript?

0 0 10

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

Để giúp các bạn có thể nâng cao trình độ tiếng Anh, Blog này mình sẽ viết bằng tiếng Anh.

Mục tiêu sẽ là, sử dụng Technical Document để học Tiếng Anh. Mình sẽ cố gắng sử dụng ngữ pháp và từ vựng đơn giản nhất (level~A1/A2) để giúp các bạn đọc nó dễ dàng hơn.


Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

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.

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 500

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 136

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 117

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 93

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 229