Object Mutability
Mutability is the ability to change a value. A mutable value can be changed, and an immutable value cannot be changed. A common misconception is that the "const" keyword makes a variable immutable.
const
In actuality, "const" only prevents reassignment. For non-object types, values can only be changed via reassignment, so declaring them with "const" actually makes them immutable. Consider, for example, the following code:
const num = 5; num = 7; // illegal reassignment of const variable
There is no way to change the value of num in this code. Note that using ++ or -- are still considered to be reassignments, and that is indicated in the error message if we try to use them on a variable declared with const.
const num = 5; num++;//illegal reassignment of constant
The resulting error is:
Uncaught TypeError: Assignment to constant variable.
const objects can be mutable
Objects are fundamentally different in regard to mutability in that their values can change without reassignment of the variable. Note that reassignment of properties is not prevented by "const". Only the variable name is prevented from reassignment.
const obj = {num: 5}; obj.num = 7; //legal obj = {num: 7}; //illegal reassignment
Objects can also have methods that change the internal values.
const obj = { num: 5, increment(){ this.num++; } } obj.increment(); console.log(obj.num); //6
Making an object immutable
It is possible to make an object actually immutable by declaring it with "const" and using Object.freeze().
const obj = {num: 5}; Object.freeze(obj); obj.num = 7; // doesn't change console.log(obj.num);// still 5
Note that if we use strict mode, the attempt to change the num value would actually cause a crash with the following error message:
Cannot assign to read only property 'num'
The use of Object.freeze() without "const" is already sufficient to make this object immutable. However, it doesn't make the variable name immutable.
let obj = {num: 5}; Object.freeze(obj); obj = {num: 5}; // new object with old name obj.num = 7; // changes successfully console.log(obj.num);// 7
What happens in this version of the code is that obj gets reassigned. The freeze() was applied to the previous object that shared the same name, but the new object was never frozen, so it is mutable.
Sealing objects
There are times when you might want to allow values in an object to change, but you don't want to allow adding or removing properties. This can be achieved by using Object.seal().
let obj = {num: 5}; Object.seal(obj); obj.num = 7; // changes console.log(obj.num);// 7 obj.newValue = 42; //cannot add new property to sealed object console.log(obj.newValue);//undefined delete obj.num; //cannot delete property from sealed object console.log(obj.num);// still exists and is 7
Granular control
Freezing and sealing apply to the whole object. If you want to make specific properties immutable, that can be done using defineProperty() or defineProperties(). The choice between these two depends on if you want to affect a single property or multiple properties.
const obj = {}; Object.defineProperty(obj, 'num',{ value: 5, writable: false, configurable: false }); obj.num = 7; // Cannot change value because writable is false delete obj.num; // Cannot delete because configurable is false console.log(obj.num);//Still exists and is 5
A new property is being defined in this example, but defineProperty() can also be used on an existing property. Note that if "configurable" was previously set to false, it cannot be changed to true, but if it was originally true, it can be set to false, since this change counts as a type of configuring.
Conclusion
In most cases, you won't need to guarantee that an object is immutable. When such a need arises, it's generally sufficient to freeze the object, but we have additional options for finer controls if such needs arise.
The above is the detailed content of Object Mutability in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)
