A Simple Guide on JavaScript Strings
This post will highlight the concept of strings and it's usage in JavaScript.
Introduction
Strings are characters written within single quotes or double quotes and stored in variables. let's consider an example below. The variables firstName and secondName store the strings “Meera” and “Menon” respectively as shownabove.
firstName = "Meera";
secondName = "Menon";How To Append Strings
Strings can be appended or added by various methods. Let's consider them one by one.
Appending with The plus (+) Operator
firstName = “Meera”;
secondName = “Menon”;
fullName = firstName + secondName;
console.log(fullName);
// “Meera Menon”
After assigning values to firstName and secondName, we create another variable fullName and use the plus operator (+) to append the first two variables firstName and secondName, the result of which is the value for fullName as shown in the console.
Appending with the (+=) operator
When you write the += with the variable message for example if you initialize a value of “Hello” to the variable , message and then you write, message += “ , World!” then, it's a shortcut for saying message = message + “ , World!”
So, instead of repeating message twice as in the above append expression, we write short form message+= instead of message = message + …..
code:
let message = “Hello”;
message += “ , World!”;
console.log(message); // “Hello, World!Please note, in above example, if we wrote message += “,World!”
Then the result in console would be “Hello,World!” without a space between “Hello” and “World!” and if we didn't write the comma then the result would be “HelloWorld!”
Appending with the concat() method
In this method we check an example to understand better:
let firstName = “Meera”;
let lastName = “Menon”;
let fullName = firstName.concat(‘‘, lastName);
console.log(FullName); // "Meera Menon"
Please note that the double slashes shown above are for commenting out the lines as these commented lines are only visible to the developer and not the user.
When to use the (+) Operator
In cases where there is only few strings or variables involved for appending, you could use the simple plus (+) Operator to concatenate strings.
When to use the (+=) Operator
When you want to append new content to an existing string variable, then you could use the (+=) Operator.
When to use the concat() method
When you want to concatenate multiple strings, then, you could use the concat() method.
Conclusion
The strings in JavaScript are versatile and you have learnt various methods to concatenate strings as demonstrated in the above examples.This is be useful while working on JavaScript projects and data structures and algorithms later that i will be covering as well.


