String Operators
String operators allow you to combine, compare, and manipulate text. While there’s only one string operator (+), understanding how strings work with operators is crucial.
String Concatenation (+)
The + operator joins (concatenates) strings together:
const firstName = 'Alice';
const lastName = 'Smith';
const fullName = firstName + ' ' + lastName;
console.log(fullName); // Alice Smith
Basic Concatenation
const greeting = 'Hello' + ' ' + 'World';
console.log(greeting); // Hello World
const message = 'I am ' + '25' + ' years old';
console.log(message); // I am 25 years old
// Concatenating multiple strings
const address = '123' + ' ' + 'Main' + ' ' + 'St';
console.log(address); // 123 Main St
Concatenating Variables
const city = 'New York';
const country = 'USA';
const location = city + ', ' + country;
console.log(location); // New York, USA
const price = 29.99;
const item = 'Book';
const message = 'The ' + item + ' costs $' + price;
console.log(message); // The Book costs $29.99
Building Complex Strings
const name = 'Bob';
const age = 30;
const job = 'Developer';
const bio = 'Name: ' + name + ', Age: ' + age + ', Job: ' + job;
console.log(bio);
// Name: Bob, Age: 30, Job: Developer
// This gets messy with many variables - use template literals instead!
Template Literals (Better Alternative)
For complex string building, template literals are much cleaner:
const name = 'Bob';
const age = 30;
const job = 'Developer';
// Old way - concatenation (messy)
const bio1 = 'Name: ' + name + ', Age: ' + age + ', Job: ' + job;
// Modern way - template literal (clean)
const bio2 = `Name: ${name}, Age: ${age}, Job: ${job}`;
console.log(bio1); // Same output
console.log(bio2); // Same output
Use template literals instead of concatenation when:
- You have multiple variables
- You need multi-line strings
- You want better readability
(See Template Literals tutorial for full details)
Concatenation with Numbers
When you mix strings and numbers with +, JavaScript converts to strings:
// String + Number = String
console.log('5' + 3); // '53' (not 8!)
console.log(5 + '3'); // '53'
console.log('Price: $' + 29.99); // 'Price: $29.99'
// All strings
console.log('2' + '2'); // '22'
// Multiple operations
console.log('5' + 3 + 2); // '532' (left to right)
console.log(5 + 3 + '2'); // '82' (5+3=8, then 8+'2'='82')
Common Gotcha
const a = '5';
const b = '3';
console.log(a + b); // '53' (string concatenation, not addition!)
// To add as numbers, convert first
console.log(Number(a) + Number(b)); // 8
console.log(parseInt(a) + parseInt(b)); // 8
Concatenation vs Other Operators
Only + concatenates - other operators convert to numbers:
console.log('10' + '5'); // '105' (concatenation)
console.log('10' - '5'); // 5 (subtraction)
console.log('10' * '5'); // 50 (multiplication)
console.log('10' / '5'); // 2 (division)
// Weird but true
console.log('5' + 3); // '53' (string)
console.log('5' - 3); // 2 (number)
Building Strings with += Operator
You can append to strings using +=:
let message = 'Hello';
message += ' ';
message += 'World';
console.log(message); // Hello World
// Building a list
let list = 'Items: ';
list += 'apple';
list += ', banana';
list += ', orange';
console.log(list); // Items: apple, banana, orange
Practical Example: Building HTML
let html = '<ul>';
html += '<li>Item 1</li>';
html += '<li>Item 2</li>';
html += '<li>Item 3</li>';
html += '</ul>';
console.log(html);
// <ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>
String Comparison Operators
You can compare strings using comparison operators:
Equality
console.log('hello' === 'hello'); // true
console.log('hello' === 'Hello'); // false (case-sensitive!)
console.log('hello' !== 'world'); // true
// Case-insensitive comparison
const str1 = 'Hello';
const str2 = 'hello';
console.log(str1.toLowerCase() === str2.toLowerCase()); // true
Alphabetical Comparison
Strings are compared alphabetically (technically, by Unicode values):
console.log('apple' < 'banana'); // true
console.log('cat' > 'dog'); // false
console.log('a' < 'b'); // true
console.log('A' < 'a'); // true (uppercase comes before lowercase)
// Multi-character comparison
console.log('abc' < 'abd'); // true
console.log('apple' < 'application'); // true
Numbers as Strings
// Be careful! Alphabetical, not numerical
console.log('10' < '9'); // true (because '1' < '9')
console.log('2' > '10'); // true (because '2' > '1')
// For numerical comparison, convert to numbers
console.log(10 < 9); // false
console.log(Number('10') < Number('9')); // false
Escaping Special Characters
Use backslash \ to include special characters:
Common Escape Sequences
| Sequence | Meaning | Example |
|---|---|---|
\' |
Single quote | 'It\'s working' |
\" |
Double quote | "She said \"Hi\"" |
\\ |
Backslash | 'C:\\folder' |
\n |
Newline | 'Line 1\nLine 2' |
\t |
Tab | 'Name:\tValue' |
\r |
Carriage return | 'Line\r\n' |
Examples
// Single quote in single-quoted string
const message = 'It\'s a nice day';
console.log(message); // It's a nice day
// Alternative: use double quotes
const message2 = "It's a nice day";
console.log(message2); // It's a nice day
// Double quote in double-quoted string
const quote = "She said \"Hello\"";
console.log(quote); // She said "Hello"
// Backslash
const path = 'C:\\Users\\Documents\\file.txt';
console.log(path); // C:\Users\Documents\file.txt
// Newline
const multiLine = 'Line 1\nLine 2\nLine 3';
console.log(multiLine);
// Line 1
// Line 2
// Line 3
// Tab
const tabbed = 'Name:\tAlice\nAge:\t25';
console.log(tabbed);
// Name: Alice
// Age: 25
Template Literals (No Escaping Needed)
// Old way - need to escape
const message = 'It\'s a "nice" day';
// New way - no escaping needed
const message = `It's a "nice" day`;
// Multi-line without \n
const html = `
<div>
<p>Paragraph</p>
</div>
`;
Common String Operations
1. Building Full Names
const first = 'John';
const middle = 'Paul';
const last = 'Doe';
const fullName = first + ' ' + middle + ' ' + last;
console.log(fullName); // John Paul Doe
// With template literal
const fullName2 = `${first} ${middle} ${last}`;
console.log(fullName2); // John Paul Doe
2. Creating Messages
const username = 'alice';
const points = 1250;
const message = 'User ' + username + ' has earned ' + points + ' points!';
console.log(message); // User alice has earned 1250 points!
// Cleaner with template literal
const message2 = `User ${username} has earned ${points} points!`;
3. Building URLs
const baseURL = 'https://api.example.com';
const endpoint = 'users';
const userId = 123;
const url = baseURL + '/' + endpoint + '/' + userId;
console.log(url); // https://api.example.com/users/123
// With template literal
const url2 = `${baseURL}/${endpoint}/${userId}`;
4. Formatting Currency
const price = 29.99;
const currency = '$';
const formatted = currency + price;
console.log(formatted); // $29.99
const formatted2 = currency + price.toFixed(2);
console.log(formatted2); // $29.99
5. Creating CSV Lines
const name = 'Alice';
const age = 25;
const city = 'New York';
const csvLine = name + ',' + age + ',' + city;
console.log(csvLine); // Alice,25,New York
// For multiple rows
let csv = 'Name,Age,City\n';
csv += 'Alice,25,New York\n';
csv += 'Bob,30,Boston\n';
console.log(csv);
Best Practices
✅ DO:
// Use template literals for complex strings
const message = `Hello, ${name}! You have ${count} items.`;
// Use single method consistently
const greeting = 'Hello' + ' ' + 'World';
// OR
const greeting = `Hello World`;
// Convert numbers when needed
const result = Number('5') + Number('3'); // 8
// Use appropriate quotes to avoid escaping
const message = "It's working";
const quote = 'She said "Hi"';
❌ DON’T:
// Don't use excessive concatenation
const msg = 'Hello, ' + name + '! You have ' + count + ' items in your ' + cart + ' cart.';
// Use template literal instead
// Don't mix string and number addition accidentally
const result = '5' + 3; // '53' (probably not intended)
// Don't create multi-line strings with \n when template literals work better
const html = '<div>\n <p>Text</p>\n</div>';
// Use template literal instead
// Don't forget case sensitivity
if (userInput === 'YES') { // Won't match 'yes' or 'Yes'
// Better: userInput.toLowerCase() === 'yes'
}
Common Mistakes
1. Accidental String Concatenation
const a = '5';
const b = '3';
// ❌ Wrong - concatenates instead of adding
const sum = a + b;
console.log(sum); // '53'
// ✅ Correct - convert to numbers first
const sum = Number(a) + Number(b);
console.log(sum); // 8
2. Missing Spaces
// ❌ Missing space
const fullName = firstName + lastName; // 'AliceSmith'
// ✅ Include space
const fullName = firstName + ' ' + lastName; // 'Alice Smith'
3. Case Sensitivity
const password = 'Secret123';
// ❌ Case-sensitive comparison
if (userInput === 'secret123') { // false if user typed 'Secret123'
// Won't match
}
// ✅ Case-insensitive comparison
if (userInput.toLowerCase() === password.toLowerCase()) {
// Will match regardless of case
}
4. Comparing Number Strings
// ❌ Alphabetical comparison
console.log('10' > '9'); // false (because '1' < '9')
// ✅ Numerical comparison
console.log(10 > 9); // true
console.log(Number('10') > Number('9')); // true
Summary
String Concatenation:
+operator joins strings:'Hello' + ' ' + 'World'+=appends to string:str += ' more'- Template literals are cleaner:
`Hello ${name}`
String + Number:
'5' + 3→'53'(concatenation)'5' - 3→2(converts to number)
Comparison:
===and!==for equality (case-sensitive)<,>for alphabetical order- Use
.toLowerCase()for case-insensitive comparison
Escaping:
\'Single quote\"Double quote\\Backslash\nNewline\tTab
Best Practice:
// Old way
const message = 'Hello, ' + name + '! You have ' + count + ' items.';
// Modern way
const message = `Hello, ${name}! You have ${count} items.`;
Next Article: String Methods