0

Can somebody explain this behaviour

Code:

name = "ABC"
console.log(name)

name[0] = "B"
console.log(name)

Output Expected:

ABC
BBC

Actual Output : Actual Output

3
  • Not only that it doesn't work, if you are in a function with strict mode ("use strict;" as the first statement), it will throw an error, for example (in Chrome) TypeError: Cannot assign to read only property '0' of string 'ABC' Commented Sep 7, 2023 at 6:08
  • He asked for the reason why I think. Strings are immutable that is the reason why his code doesn't work Commented Sep 7, 2023 at 6:08
  • A quote from MDN: When using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. Commented Sep 7, 2023 at 6:12

2 Answers 2

5

Strings are immutable/readonly due to the fact that they are primitive data types in JavaScript. You can only generate new strings.

name = "ABC"
console.log(name)

name = "B" + name.slice(1);
console.log(name)

To read more about primitives-MDN-Primitives

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

Comments

0

By creating a new string with the desired modification, you achieve the desired result while keeping the original name variable intact.

let name = "ABC";
console.log(name);

name = "B" + name.substring(1); // Concatenate "B" with the rest of the string
console.log(name);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.