To append a string in JavaScript, combine the existing string with the text you want to add and assign the result back to a variable. You can use the `+=` operator, the `+` operator, or a template literal; the best choice depends on whether you are extending a variable or building a new string.
Strings are immutable in JavaScript, which means an existing string’s contents do not change in place. An append expression produces a new string, so saving that result is essential when you want to keep it.
What You’ll Need
- A JavaScript environment, such as a browser’s developer console or a JavaScript file you can run.
- A string variable or a starting string, plus the text you want to add.
- Basic familiarity with assigning values to variables. The examples use
letwhen the variable will be reassigned.
Step-by-Step
- Choose the starting string. Declare a variable with
letif you plan to append to it. For example:let message = "Hello";. The variable now refers to the stringHello. - Use
+=to append directly to that variable. Writemessage += " there";. This is shorthand for assigning the old value joined with the new text:message = message + " there";. After the statement runs,messagecontainsHello there. - Include any needed spaces or punctuation yourself. JavaScript joins the characters exactly as supplied; it does not add a separator automatically. Appending
"there"to"Hello"givesHelloThereonly if capitalization is already present, orHellothereotherwise. Use" there"to create a space, or append punctuation explicitly. - Use
+when you want to create a result without changing the original variable. For example:const first = "Good";followed byconst greeting = first + " morning";. The new variable holdsGood morning, whilefirststill holdsGood. This is useful when the original value should remain available. - Use a template literal when the appended text includes variables. Put the whole string inside backticks and place an expression in
${...}:let name = "Ari";thenlet greeting = `Hello, ${name}!`;. The result isHello, Ari!. Template literals are especially readable when a string combines fixed text and several values. - Check the result. Log the variable with
console.log(message);or inspect it in your environment. Confirm the new content, spacing, punctuation, and capitalization. If the value is displayed in a page or used in another operation, test it there too.
Here is a complete example using +=:
let status = "Loading";
status += " complete.";
console.log(status); // Loading complete.
The key part is the assignment. Writing status + " complete."; calculates a combined string but discards the result. Writing status += " complete."; stores the result back in status.
Common Mistakes
- Forgetting to assign the result. Because strings are immutable,
text + " more";does not updatetext. Usetext += " more";or save the expression in another variable. - Expecting JavaScript to add a space. The operator joins exactly what is on either side. If a separator is needed, include it in the appended string, such as
" more", or add it as a separate expression. - Trying to reassign a
constvariable. A declaration such asconst text = "Start";cannot later be updated withtext += " end";. Useletwhen you intend to reassign the variable. You can still useconstfor a separate result that is assigned only once. - Appending a value that is not a string. The
+operator can perform addition when both operands are numbers, and it can convert other values to strings in a mixed expression. For predictable output, convert a value explicitly withString(value)when necessary, and check what the value represents. - Confusing a string with an array. Strings and arrays are different types. String concatenation joins text; array methods such as
push()add elements to an array. If the goal is to store several separate pieces, an array may be a better fit. - Using the wrong quote character for a template literal. Interpolation with
${...}works inside backticks, not ordinary single or double quotes. For example,`Hello, ${name}`inserts the value, while"Hello, ${name}"contains the characters literally.
Tips
Use += when the intention is plainly “extend this variable.” It is concise and familiar for a small number of additions. Use + when you want to keep the starting value unchanged, and use a template literal when inserted values make the expression easier to read.
For a value that may be missing, decide what should happen before appending. Concatenating a missing value can produce unexpected text such as undefined or null. A fallback can make the behavior explicit: let label = input ?? ""; followed by label += " confirmed";. The nullish coalescing operator uses the fallback only when the value is null or undefined; it does not replace an empty string.
If you are combining many pieces, a template literal can keep a short expression readable. For a larger collection of pieces, storing them in an array and joining them with join() may make separators easier to manage. Choose based on clarity rather than assuming that one form is always best.
When the appended text comes from user input, treat it as data rather than trusted page markup. Assigning text through a text-only DOM property is generally safer for displaying plain text than interpreting a string as HTML. The string operation itself does not sanitize or validate content.
Troubleshooting
The variable has not changed: Look for an expression that uses + without assigning the result. Replace it with variable += addition; or save the combined value in a new variable. Also check whether the code path containing the assignment actually runs.
You see an error about assigning to a constant: The variable was declared with const. If reassignment is intended, declare it with let. If the original should stay fixed, calculate the appended value in a separate variable instead.
The output has missing or doubled spaces: Inspect the start and end of both strings. Add a space in exactly one place if the boundary needs one. Logging a quoted or otherwise clearly delimited value can help reveal invisible whitespace, for example console.log(`[${message}]`);.
The output contains undefined, null, or an unexpected number: Check the value being appended before joining it. Confirm that it exists and has the type you expect. Convert it deliberately with String(value), or provide a suitable fallback if missing data should contribute no text.
The template shows ${name} literally: Make sure the string uses backticks and that the expression is written with the dollar sign and braces. Check that the variable name is spelled correctly and is available where the template is created.
Frequently Asked Questions
How do I append a string to a variable in JavaScript?
Use variable += " text";. The operator combines the current string with the new text and assigns the result back to the variable.
Can I append to a string declared with const?
Not by reassigning that variable. Use let if the string variable needs to change, or create a new const variable for the combined result.
Does + change the original string?
No. Strings are immutable. The + operator returns a new combined string; you must assign that result if you want to keep it.
How can I append a variable inside a string?
Use a template literal, such as `Hello, ${name}`, or concatenate with +. Backticks are required for template literal interpolation.
How do I append a string to an array?
If you mean adding a string as a separate array element, use array.push("text"). If you mean joining text onto one string stored in a variable, use string concatenation instead.
Is += the only way to append?
No. You can use variable = variable + addition, or create a new value with + or a template literal. Choose the form that makes reassignment and the intended result clear.