Problem Statement
Are strings mutable or immutable in JavaScript?
Explanation
Strings are immutable in JavaScript. Once created, you cannot change individual characters.
Attempts to modify characters are ignored in non-strict mode or throw errors in strict mode.
String methods like replace, toUpperCase, and slice create new strings instead of modifying the original.
You can reassign the variable to a new string, but the original string value never changes.
This is different from arrays, which are mutable.
Immutability makes strings safer and more predictable.
Code Solution
SolutionRead Only
let str = 'Hello';
// Cannot change individual characters
str[0] = 'J';
console.log(str); // 'Hello' (unchanged)
// In strict mode, this would throw an error
'use strict';
// str[0] = 'J'; // TypeError in strict mode
// String methods create new strings
let original = 'hello';
let upper = original.toUpperCase();
console.log(original); // 'hello' (unchanged)
console.log(upper); // 'HELLO' (new string)
let text = 'JavaScript';
let replaced = text.replace('Java', 'Type');
console.log(text); // 'JavaScript' (unchanged)
console.log(replaced); // 'TypeScript' (new string)
// Can reassign variable (not modifying string)
let name = 'John';
name = 'Jane'; // New string assigned
// Compare with mutable arrays
let arr = [1, 2, 3];
arr[0] = 10; // Works! Arrays are mutable
console.log(arr); // [10, 2, 3]Practice Sets
This question appears in the following practice sets:
