Strings are Immutable in JS
The immutability of strings in JavaScript
In JavaScript, strings are immutable, which means that once they are created, they cannot be changed. This means that any operation on a string will always return a new string rather than modifying the original string itself.
Example 1:
let str = "Hello"; let newStr = str.concat(" World"); console.log(str); // Output: "Hello" console.log(newStr); // Output: "Hello World"
In the example above, the `concat()` method is used to concatenate the string " World" to the original string "Hello". However, the `concat()` method does not modify the original string, it returns a new string that contains the concatenated values.
Points to note:
1. Strings are immutable in JavaScript, meaning they cannot be changed after they are created.
2. Operations on strings always create new strings.
3. Methods like concat(), slice(), trim(), etc., that appear to modify strings actually return a new string instead.
4. The original string remains unchanged.
5. In JavaScript, strings are considered primitive values. This means they are immutable by nature.
Example 2:
let str1 = "JavaScript"; let str2 = str1.slice(0, 4); // returns a new string "Java" console.log(str1); // Output: "JavaScript" console.log(str2); // Output: "Java"
In the example above, the `slice()` method is used to extract the substring "Java" from the original string "JavaScript". However, the `slice()` method does not modify the original string, it returns a new string that contains the extracted substring.
Immutability in Function Parameters:
function modifyString(s) { s = s.toUpperCase(); // Creates a new string inside the function return s; } let original = "abc"; let modified = modifyString(original); console.log(original); // Output: "abc" console.log(modified); // Output: "ABC"
Benefits of Immutability:
- Predictability: Immutability leads to more predictable code behavior since you don't have to worry about unexpected changes to shared data.
- Functional Programming: Immutability is a key concept in functional programming, enabling easier reasoning about code and minimizing side effects.
- Performance Optimizations: Some JavaScript engines can optimize immutability patterns, making certain operations faster (like debugging).
Key takeaways:
- String in JS are immutable, they cannot be changed once created.
- Operations on strings always return a new string.
- Methods like concat(), slice(), etc., do not modify the original string, they return a new string instead.
Comments
Post a Comment