DEV Community

Cover image for Mastering Concatenation in JavaScript
Adijat Motunrayo Adeneye
Adijat Motunrayo Adeneye

Posted on

Mastering Concatenation in JavaScript

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

OR

let firstname = "Motunrayo";
let lastname = "Adeneye";
console.log(firstname + " " + lastname);//Motunrayo Adeneye

Enter fullscreen mode Exit fullscreen mode

Using += operator

This require the combination of addition sign and assignment equator.

let job = "frontend";
job+= " developer";
console.log(job)//frontend developer
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Using the concat() method

This method is used to concatenate string together

let word = "Java";
let result = word.concat("script");
console.log(result); //Javascript
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

We have come to the end of this article. Hope you are learnt about concatenation.

Top comments (0)