How to Create String in JavaScript: Simple Syntax and Examples
In JavaScript, you create a
string by enclosing text in single quotes ' ', double quotes " ", or backticks ` `. Backticks allow embedding expressions using ${} for dynamic strings.Syntax
You can create strings in three ways:
- Single quotes: Enclose text in
' '. - Double quotes: Enclose text in
" ". - Backticks (template literals): Enclose text in
` `to allow embedding variables or expressions.
javascript
const singleQuoteString = 'Hello'; const doubleQuoteString = "World"; const templateLiteral = `Hello, ${doubleQuoteString}!`;
Example
This example shows how to create strings using all three methods and how template literals let you add variables inside strings easily.
javascript
const name = 'Alice'; const greeting1 = 'Hello, ' + name + '!'; const greeting2 = "Hello, " + name + "!"; const greeting3 = `Hello, ${name}!`; console.log(greeting1); console.log(greeting2); console.log(greeting3);
Output
Hello, Alice!
Hello, Alice!
Hello, Alice!
Common Pitfalls
Common mistakes include mixing quote types without escaping and forgetting to use backticks for template literals when embedding variables.
Wrong: const wrong = 'Hello, ${name}!'; (this will not replace ${name})
Right: const right = `Hello, ${name}!`;
javascript
const name = 'Bob'; const wrong = 'Hello, ${name}!'; const right = `Hello, ${name}!`; console.log(wrong); console.log(right);
Output
Hello, ${name}!
Hello, Bob!
Quick Reference
| Method | Syntax | Use Case |
|---|---|---|
| Single quotes | 'text' | Simple strings without variables |
| Double quotes | "text" | Simple strings without variables |
| Backticks | `text ${expression}` | Strings with variables or expressions |
Key Takeaways
Create strings using single quotes, double quotes, or backticks in JavaScript.
Use backticks (template literals) to embed variables or expressions inside strings.
Avoid mixing quote types without escaping to prevent syntax errors.
Remember that variables inside single or double quotes are not replaced automatically.
Use template literals for cleaner and more readable string concatenation.