Date:

Share:

How to Join/Concatenate Strings in JavaScript

Related Articles

introduction

Strings are one of the most common types of data used in software – they represent strings of characters that we analyze as words.

Chaining strings is a pretty standard task, especially since we do not always deal with static strings. We often create strings dynamically, as with ES6 templates, or simply string strings to create new strings.

If you want to read more about creating strings in a dynamic format – read our guide to ES6 templates / strings in Node.js!

In this tutorial, we will review how to join / add / string strings in JavaScript.

Note: Strings are Unchangeable, Which means you can not really change them. Each time you call a string change action, a copy is built with the applied changes and is returned in its original place.

Threading with operator +

The easiest, and probably most intuitive, approach to stringing strings is to use + sets off:

console.log("hello " + "world");

Running this short code snippet leads to:

hello world

You can assign a string in memory to a reference variable, and refer to an object instead of stringing it directly:

let firstWord = "hello ";
let secondWord = "world";
let newWord = firstWord + secondWord;

It also causes:

hello world

Note: In most cases, you can replace the a = and + With the abbreviation +=, Which allows you to omit the Reference to the first operand, Which will be replaced with the variable to which you assign the result.

Instead, you can write the short version:

let word = "hello ";
word += "world";
console.log(word);

It is worth noting that other data types can also be thrown into the mix, and whenever implicit conversion is allowed – JavaScript will “fit” the data types into strings.

For example, integers are easily converted to strings, so if you try to string an integer to a string – the integer will be converted before adding it. It is not possible to convert a string to an integer at any time – for example when it does not represent a number or has a strange design, so it is usually easier to convert To String, than M necklace:

var str = "hello";
var int = 21;
var boolean = true;

console.log(str+int);
console.log(str+boolean)

This causes both the Boolean number and the integer to be converted to string representations and then attached to the “hello” string:

hello21
hellotrue

String.prototype.concat ()

God concat() The method was created specifically for this task – to For threading Strings. It can be run over any string, and gets an additional string that will be threaded to the one calling.

In a sense, it is similar to the use of the short hand += sets off:

let string1 = "Java";
let string2 = "Script";

console.log(string1.concat(string2));

This is the result:

JavaScript

Refer to our practical and practical guide to learning Git, with best practices, industry-accepted standards and a cheat sheet included. Stop Google Git commands and actually Learn It!

In addition, you can specify a boundary as the first argument, which is then added between all the threaded strings:

let string1 = "Java";
let string2 = "Script";

console.log(string1.concat(", ", string2));

This is the result:

Java, Script

Array.prototype.join ()

God join() Method e Array class is used to connect array components to a string, with a default comma separator (,).

This allows us to handle a larger number of strings in a much more concise way, and it is not uncommon to read a file into an array, or work with an array of strings that you want to join together.

If you do not pass any arguments to the method – the default value will be used to delimit the new strings that have joined. Let’s pass an empty string to skip it and just join them similar to what we’ve seen before:

let elements = ["JavaScript", "HTML", "CSS"];
console.log(elements.join(""));

This is the result:

JavaScriptHTMLCSS

Which approach to use?

It is recommended Prefer the concat() Function instead of operator +, Due to performance benefits. However, this does not always hold and takes into account a number of assumptions.

First of all – the number of strings you thread plays a role in this, as well as other factors you may not even be aware of. Let’s look at the concat() The method as well as the + sets off:

console.time('Concatenating with Operator');
concatWithOperator();
console.timeEnd('Concatenating with Operator');

console.time('Concatenating with Function');
concatWithFunction();
console.timeEnd('Concatenating with Function');

function concatWithOperator() 
    let result = "";
    for (let i = 0; i < 10000; i++) 
      result = result += i;
    


function concatWithFunction() 
    let result = "";
    for (let i = 0; i < 10000; i++) 
      result = result.concat(i);
    

This is the result:

Concatenating with Operator: 3.232ms
Concatenating with Function: 1.509ms

But wait, let’s change the environment and run it on another computer:

Concatenating with Operator: 1.985ms
Concatenating with Function: 1.990ms

And let’s run it on him Machine again:

Concatenating with Operator: 2.030ms
Concatenating with Function: 0.934ms

Execution times vary greatly (although all are quickly accepted). It is also worth noting the official statement from MDN, Regarding performance benefits:

It is highly recommended to use the allocation (+, + =) operators instead of the concat () method.

Which may seem strange, given this fact concat() Exceeds the operators in tests or in the worst case is him speed. What gives? Well, comparing code like this is not as easy as just running it and watching the results.

Your browser, its version, as well as the optimization tools it uses may vary from machine to machine, and features like these really affect performance. For example, we used Different strings In a thread, those created from iteration. If we were to use the same string, an optimizer like Google’s V8 would have further optimized the use of the string.

Check and verify your code Instead of getting advice as a face value. Not all machines and environments are the same, and what works great in one may not work well in another. Keep this in mind when creating applications.

Summary

We tested how to string strings in JavaScript using e + Operator, e join() Method e Arrays The class as well as the concat() Method e String status.

We checked the official position and did our own tests to see which approach is the most effective – and as usual, it depends on various factors.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles