Interesting Facts About JavaScript Strings
Let's see some interesting facts about JavaScript strings that can help you become an efficient programmer.
Strings are Immutable
In JavaScript, strings are immutable, which means once you create a string, you cannot change its characters individually. Any operation that appears to modify a string, like replace() or concat(), actually creates a new string.
let s = "hello";
s[0] = "H"; // Won't work
console.log(s); // Still "hello"
Output
"hello"
Using Template Literals
Template literals, introduced in ES6, allow for writing expressions directly into strings using backticks ` and ${} syntax.
let s1 = "Sourav";
let s2 = `Hi, ${a}!`;
console.log(s2);
Output
"Hi, Sourav!"
String Comparison
JavaScript compares strings letter by letter. This makes JavaScript strings different from some languages that use locale-based comparisons.
console.log("apple" > "banana");
Output
false
Strings as Arrays of Characters
We can access JavaScript strings just like as in JavScript Arrays to get the individual character.
let s = "hello";
console.log(s[1]);
Output
"e"
String Methods Create Copies
When you call a method like toUpperCase() or slice(), it returns a modified copy of the original string. The original string remains unaffected.
let s1 = "hello";
let s2 = s1.toUpperCase();
console.log(s2);
console.log(s1);
Output
"HELLO"
"hello"
Splitting and Joining Strings
The split() method allows you to break a string into an array, and join() does the opposite by joining elements of an array into a single string.
let s1 = "apple,banana";
let s2 = s1.split(",");
console.log(s2);
console.log(s2.join(" & "));
Output
["apple", "banana"]
"apple & banana"
Add Padding with padStart() and padEnd()
ES2017 introduced padStart() and padEnd() by which we can add padding characters to the beginning or end.
let s = "5";
console.log(s.padStart(3, "0"));
console.log(s.padEnd(3, "-"));
Output
"005"
"5--"
Reversing a String
Although JavaScript doesn’t have a built-in reverse method for strings, you can reverse a string by combining split(), reverse(), and join() methods.
let s1 = "hello";
let s2 = s1.split("").reverse().join("");
console.log(s2);
Output
"olleh"
String Length as a Property
Unlike arrays, you can get the length of a string directly with .length.
let s = "hello";
console.log(s.length);
Output
5
Working with Multi-Line Strings
Template literals allow to write multi-line strings without using escape characters (\n).
let s = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you!`;
console.log(s);
Output
Roses are red,
Violets are blue,
JavaScript is fun,
And so are you!
Check for Substrings Easily
JavaScript provides includes(), startsWith(), and endsWith() methods, which makes easy to check substrings.
let s = "JavaScript is great";
console.log(s.includes("JavaScript"));
console.log(s.startsWith("Java"));
console.log(s.endsWith("great"));
Output
true
true
true