Hey there 👋, This article is for those who are getting started with concatenation or who are familiar with it. Let's dive in
Introduction
Concatenation is the joining of two or more strings together. It exist among strings. Concatenation is a fundamental concept that give clarity and readability especially when reused.
In this guide, we will be exploring at different ways to concatenate strings.
Using +
operator
This is the use of addition operator to concatenate string
let firstname = "Motunrayo";
let lastname = "Adeneye";
console.log(firstname + lastname)//MotunrayoAdeneye
By default, there is no space between the name. To include space.
let firstname = "Motunrayo ";
let lastname = "Adeneye";
console.log(firstname + lastname);Motunrayo Adeneye
Alternatively
let firstname = "Motunrayo";
let lastname = "Adeneye";
console.log(firstname + " " + lastname);//Motunrayo Adeneye
Using +=
operator
This combines addition sign +
and assignment equator =
.
let job = "frontend";
job+= " developer";
console.log(job)//frontend developer
Using template literals
This requires the use of backtick (
)
to allow the use of declared variables.
let name = "Motunrayo"
let age = 30;
let about = `Hello, My name is ${name}. I am ${age} years old`;
console.log(about); //Hello, My name is Motunrayo. I am 30 years old
Using the concat()
method
It is javascript built in method for combining string together.
let word = "Java";
let result = word.concat("script");
console.log(result); //Javascript
Using join()
method
This method is used to join array that containing strings together
let colors = ["red", "blue", "yellow"];
console.log(colors)//["red", "blue", "yellow"]
let result = colors.join(",");
console.log(result); //red, blue, yellow
Conclusion
We've reached the end of this guide on string concatenation in JavaScript. I hope you’ve learned something new or reinforced your understanding of this essential concept.
Got questions or comments? Feel free to share them below! 😊
Top comments (0)