📌 Understanding String Concatenation in JavaScript
String concatenation is the process of joining two or more strings together using the
+ operator.
🔹 Basic String Concatenation
alert("Thanks for your input!");
OR
var message = "Thanks for your input!";
alert(message);
🔹 Concatenating Variables and Strings
If a user enters their name (userName), you can personalize a message:
var userName = "Susan";
alert("Thanks, " + userName + "!");
✔️ The + operator joins the strings.
✔️ Make sure to include spaces inside the strings to avoid "Thanks,Susan!" instead of
"Thanks, Susan!".
🔹 Concatenating Multiple Variables
var message = "Thanks, ";
var banger = "!";
alert(message + userName + banger);
✔️ This approach separates different parts of the message for better readability.
🔹 Assigning a Concatenation to a Variable
var message = "Thanks, ";
var userName = "Susan";
var banger = "!";
var customMess = message + userName + banger;
alert(customMess);
✔️ The value of customMess becomes "Thanks, Susan!".
🔹 Concatenating Numbers as Strings
If numbers are in quotes, JavaScript treats them as strings and joins them instead of
adding:
alert("2" + "2"); // Output: "22"
✔️ Instead of adding 2 + 2 = 4, JavaScript joins the "2" and "2" into "22".
🔹 Mixing Strings and Numbers
alert("2 plus 2 equals " + 2 + 2); // Output: "2 plus 2 equals 22"
🚨 Why?
is a string.
"2 plus 2 equals "
The + operator first concatenates the string with 2, resulting in "2 plus 2 equals 2".
Then, another + 2 is added as a string, so the final result is "2 plus 2 equals 22".
✔️ To fix this and get "2 plus 2 equals 4", use parentheses:
alert("2 plus 2 equals " + (2 + 2)); // Output: "2 plus 2 equals 4"
💡 Quick Summary
✔️ Use the + operator to concatenate strings.
✔️ Include spaces inside strings to maintain formatting.
✔️ Numbers in quotes act like strings and are concatenated instead of added.
✔️ Use parentheses () to perform arithmetic inside a string.