Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

As mentioned above, the sort method cannot sort frozen arrays. This article will learn about freezing arrays and objects in detail.

Object.freeze( Object || Array )

Object. Freeze (Object | | Array), an Object can be frozen, into an immutable Object. This approach increases the reliability of our program.

Once we have created a solid Object, we can use the object.freeze (obj) method to freeze the Object to prevent it from being corrupted or tampered with by other methods.

Security brought by immutable objects is very important for the actual work development at this stage. It seems to have become common practice to install all sorts of untrusted code on the system.

Immutable objects provide good interface protection, immutable objects can make code more reliable, more secure,

Note: Shallow freezing

The Object. Freeze (obj) method, however, is similar to “shallow copy” and only freezes the top-level attributes of an Object, not a deep freeze.

Object.freeze(obj)const objThe difference between

Freeze array

Let’s freeze an array

let my_array = ['xn213'.'rainbows'.'beauty'.'moments']
Object.freeze(my_array)
my_array.sort()
Copy the code

The code above runs in the Chrome Console panel as follows:

Const defines a variable obj

We know that const is also immutable, as follows

const OBJ = 'This OBJ is immutable.'

OBJ = 'To change is to try! '

console.log(OBJ)
Copy the code