Home > Web Front-end > Front-end Q&A > Why are strings immutable in javascript?

Why are strings immutable in javascript?

青灯夜游
Release: 2022-02-16 14:47:45
Original
3447 people have browsed it

In JavaScript, the value of a string is immutable, which means that once a string is created, it cannot be changed; reason: the string itself is a basic type encapsulated by the language, and the underlying type is An object whose contents cannot be changed since its creation, so the string remains unchanged.

Why are strings immutable in javascript?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In JavaScript, the value of a string is immutable, which means that once the string is created, it cannot be changed.

For example, the following code:

var myStr = "Bob";
myStr[0] = "J";
Copy after login

will not change the value of the variable myStr to "Job" because the variable myStr is immutable.

Note that this does not mean that myStr can never be changed, only that the individual characters of the string literal cannot be changed.

The only way to change myStr is to reassign it a value, like this:

var myStr = "Bob";
myStr = "Job";
Copy after login

Why are strings immutable in js?

In fact, the string itself is a basic type encapsulated by the language (output through the system's own String constructor new). The bottom layer is still an object, not a simple data type. The content of this object cannot be changed since it was created, so the string remains unchanged. Operations such as

will only generate new string objects, and the original string objects will not change. If a string object is no longer referenced, it will be recycled by GC.

[Related recommendations: javascript learning tutorial]

The above is the detailed content of Why are strings immutable in javascript?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template