Can somebody explain this behaviour
Code:
name = "ABC" console.log(name) name[0] = "B" console.log(name)
Output Expected:
ABC BBC
Actual Output :
2
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
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);
Click here to cancel reply.
2
Answers
Strings are immutable/readonly due to the fact that they are primitive data types in JavaScript. You can only generate new strings.
To read more about primitives-MDN-Primitives
By creating a new string with the desired modification, you achieve the desired result while keeping the original name variable intact.