1

Javascript has a number of string manipulation operations which can be performed on it. So we have methods like concat(), slice(), match(), etc

My question is do all these string manipulation methods return a new string value as the result OR are there some methods which actually modify the actual string being used in the method ?

1

3 Answers 3

3

Strings in JavaScript (and many other languages) are implemented as immutable objects. This has a few beneficial properties:

  1. It's thread safe, and more specifically,
  2. Multiple references to the same string can be kept safely without having to worry that the value changes.

This also means that all string methods must return a new string if they aim to modify the original value.

Sign up to request clarification or add additional context in comments.

3 Comments

You can verify this very easily. Try to run String.prototype.mutate = function (arg) { this = 'changed' } and JS interpreters will complain that you are supplying an invalid left-hand side in assignment.
@LimH. That's not actually unique to String. this can't be set in any function as it's not a variable.
@JonathanLonowski oh wow. Yet another time I completely misunderstood JS
0

The return value is a clone of the original string.

In other words, calling concat, match or slice will not modify the original string.

You can always refer to the MDN reference for documentation

But, to quote from the source

Concat

Combines the text of two or more strings and returns a new string.

Comments

0

Strings are immutable, and once they are created they even cannot be modified again.

Mdn:

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string, for example, a substring of the original (by picking individual letters or using String.substr()) or a concatenation of two strings using the concatenation operator (+) or String.concat().

Therefore, yes. Every String operation returns a new String

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.