Home >Web Front-end >JS Tutorial >Mastering Concatenation in JavaScript

Mastering Concatenation in JavaScript

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 07:14:15228browse

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

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.

The above is the detailed content of Mastering Concatenation in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn