Table of contents
1.
Introduction
2.
What is Concatenate in JavaScript?
3.
5 Ways to Concatenate Strings in JavaScript
4.
Using String concat() Method
4.1.
Syntax
4.2.
Example:
4.3.
JavaScript
5.
Using + Operator
5.1.
Syntax
5.2.
Example
5.3.
JavaScript
6.
Using Array join() Method
6.1.
Syntax
6.2.
Example
6.3.
JavaScript
7.
Using Template Literals (Template Strings)
7.1.
Syntax
7.2.
Example
8.
Using String fromCharCode and reduce
8.1.
Syntax
8.2.
Example
9.
Example of JavaScript Concatenate
9.1.
Explanation of the Program
9.2.
Concatenation Methods
10.
Frequently Asked Questions
10.1.
How to set concatenate in JavaScript?
10.2.
How to concatenate a list in JavaScript?
10.3.
Why would I choose concat() over the + operator?
11.
Conclusion
Last Updated: Nov 2, 2024
Easy

How to Concatenate Strings in Javascript?

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In JavaScript, concatenating strings means joining two or more strings together to form one single string. The concat method in JavaScript helps you combine strings easily. The concat method in JavaScript provides an efficient way to achieve this, allowing developers to merge strings seamlessly.

Concatenate Javascript

In this article, we will learn various methods for string concatenation in JavaScript.

What is Concatenate in JavaScript?

In JavaScript, concatenation refers to the process of joining two or more strings together to form a single string. This can be done using various methods, allowing for flexibility in how strings are combined. Understanding string concatenation is essential for effective string manipulation in programming.

5 Ways to Concatenate Strings in JavaScript

There are several methods to concatenate strings in JavaScript. You can use the + operator, the concat() method, template literals, the join() method from arrays, and the Array.prototype.reduce() method. Each approach has its own use cases and benefits, making it important to choose the right one based on your specific needs.

There are 5 Ways to concatenate Strings in Javascript  - 
 

  1. Using String concat() Method
     
  2. Using + Operator
     
  3. Using Array join() Method
     
  4. Using Template Literals (Template Strings)
     
  5. Using String fromCharCode and reduce

Using String concat() Method

The concat() method is a straightforward way to join strings together. Think of it as adding one string to the end of another. Here's how it works:

Syntax

string1.concat(string2);

Example:

  • JavaScript

JavaScript

let greeting = "Hello, ";

let name = "Alice!";

let welcomeMessage = greeting.concat(name);

console.log(welcomeMessage);
You can also try this code with Online Javascript Compiler
Run Code


Output:

"Hello, Alice!"

In this example, concat() takes the string "Alice!" & adds it to the end of "Hello, ", resulting in "Hello, Alice!". It's simple & works well when you're dealing with a couple of strings.

Using + Operator

The + operator is not just for adding numbers; it's also for combining strings. It's like saying "this plus this". It's probably the most used method because it's intuitive & flexible:

Syntax

string1 + string2;

Example

  • JavaScript

JavaScript

let part1 = "How are ";

let part2 = "you doing?";

let sentence = part1 + part2;

console.log(sentence);
You can also try this code with Online Javascript Compiler
Run Code


Output: 

"How are you doing?"

Here, we simply put part1 & part2 together with a + in between. The result is a seamless combination of both strings.

Using Array join() Method

When you have several strings in an array & you want to combine them, the join() method is your friend. It's like stringing beads onto a thread. You can even specify what goes between the strings, like a comma or space:

Syntax

array.join('');

Example

  • JavaScript

JavaScript

let words = ["Joining", "strings", "with", "join()"];

let sentence = words.join(" "); // The space (" ") is what we're using to join the strings

console.log(sentence);
You can also try this code with Online Javascript Compiler
Run Code


Output: 

"Joining strings with join()"

This method is especially handy when you're dealing with a list of strings & want more control over how they're combined.

Each of these methods has its place & choosing the right one depends on what you're trying to achieve. Whether you're building a greeting message, forming a question, or putting together sentences from an array of words, JavaScript offers you the tools to concatenate strings effectively.

Using Template Literals (Template Strings)

Template literals are a powerful feature in JavaScript that allow you to embed expressions within string literals. They are enclosed by backticks (`) instead of single or double quotes. This method provides an easy way to concatenate strings and variables.

Syntax

let greeting = `Hello, ${name}!`;

Example

let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting);
You can also try this code with Online Javascript Compiler
Run Code


Output:

Hello, Alice!

Using String fromCharCode and reduce

The String.fromCharCode() method is used to create a string from the specified sequence of Unicode values. You can also use the reduce() method on an array to concatenate characters into a single string.

Syntax

let str = array.reduce((accumulator, current) => accumulator + String.fromCharCode(current), "");

Example

let charCodes = [72, 101, 108, 108, 111]; // Unicode values for "Hello"
let str = charCodes.reduce((acc, code) => acc + String.fromCharCode(code), "");
console.log(str);
You can also try this code with Online Javascript Compiler
Run Code

Output:

Hello

Example of JavaScript Concatenate

This complete example demonstrates how you can use the concat() method, the + operator, and the join() method in a single program to achieve different string concatenation tasks, offering flexibility and control over how you construct strings in JavaScript.

// Function to ask the user for inputs (mocked for this example)

function getUserInput(prompt) {
    // In a real program, you might use window.prompt(prompt) in the browser to get user input
    // For demonstration, we'll just return some example responses
    let responses = {
        "Enter a name": "Alex",
        "Enter a location": "the park",
        "Enter an activity": "jogging"
    };
    return responses[prompt];
}


// Using the concat() method

let name = getUserInput("Enter a name");
let greeting = "Hello, ".concat(name, "! ");
// Using the + operator
let location = getUserInput("Enter a location");
let activity = getUserInput("Enter an activity");
let actionSentence = "Today, " + name + " went to " + location + " for " + activity + ". ";


// Using the array join() method

let storyParts = [
    greeting,
    actionSentence,
    "It was a beautiful day, and everyone was having a great time."
];
let fullStory = storyParts.join("\n");
/ Displaying the story
console.log(fullStory);

Explanation of the Program

Mock User Input: Since we're running this in a static environment, the getUserInput function simulates getting user input by returning predefined responses. In a real application, you might use prompt() in a browser environment to get this input from the user.

Concatenation Methods

  • concat() Method: We start with a simple greeting using the concat() method, combining "Hello, " with the user's name and an exclamation mark to form a greeting.
     
  • + Operator: Next, we construct a sentence describing an action using the + operator, combining text with the user's inputs for name, location, and activity.
     
  • join() Method: Lastly, we use the join() method to put together the greeting, the action sentence, and a closing sentence into a full story, separating them with newline characters for readability.
     
  • Output: The program prints out a simple, coherent story constructed from the user's inputs and additional text, showcasing the different string concatenation methods in JavaScript.

Frequently Asked Questions

How to set concatenate in JavaScript?

To concatenate strings in JavaScript, you can use the + operator or the concat() method to join two or more strings together.

How to concatenate a list in JavaScript?

To concatenate lists (arrays) in JavaScript, use the concat() method or the spread operator (...) to combine two or more arrays into one.

Why would I choose concat() over the + operator?

While both can be used for string concatenation, concat() can be more readable when concatenating multiple strings in one go, as it clearly separates each string being concatenated. The + operator, however, is more versatile and commonly used, as it can handle both strings and numbers seamlessly.

Conclusion

In this article, we learned the art of concatenating strings in JavaScript, a fundamental skill that finds use in countless coding scenarios. We explored three main approaches: the concat() method for merging strings in a clear, methodical manner; the versatile + operator, ideal for quick and straightforward concatenations; and the join() method, best suited for combining arrays of strings with precise control over separators.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass