Introduction
Concatenation is the joining of two or more strings together. String is a primitive data type that are enclosed within single quotes ' '
or double quotes " "
. Concatenation helps to give clarity and readability especially when reused.
In this guide, we will be looking 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
You will notice that there is no space between the name. For space to be between them.
let firstname = "Motunrayo ";
let lastname = "Adeneye";
console.log(firstname + lastname);Motunrayo Adeneye
OR
let firstname = "Motunrayo";
let lastname = "Adeneye";
console.log(firstname + " " + lastname);//Motunrayo Adeneye
Using +=
operator
This require the combination of addition sign and assignment equator.
let job = "frontend";
job+= " developer";
console.log(job)//frontend developer
Using template literals
This require 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
This method is used to concatenate 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
We have come to the end of this article. Hope you are learnt about concatenation.
Top comments (0)