totn JavaScript

JavaScript: String concat() method

This JavaScript tutorial explains how to use the string method called concat() with syntax and examples.

Description

In JavaScript, concat() is a string method that is used to concatenate strings together. The concat() method appends one or more string values to the calling string and then returns the concatenated result as a new string. Because the concat() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the concat() method is:

string.concat(value1, value2, ... value_n);

Parameters or Arguments

value1, value2, ... value_n
The values to concatenate to the end of string.

Returns

The concat() method returns a new string that results from concatenating the original string with the string values that were passed in as parameters.

Note

  • Each of the parameter values will be converted to a string, if necessary, before the concatenation operation is performed.
  • The concat() method does not change the value of the original string.
  • You can also use the + operator to concatenate values together.

Example

Let's take a look at an example of how to use the concat() method in JavaScript.

For example:

var totn_string = 'Tech';

console.log(totn_string.concat('On','The','Net'));

console.log(totn_string);

In this example, we have declared a variable called totn_string that is assigned the string value of 'Tech'. We have then invoked the concat() method of the totn_string variable to append the three string values to the end of the value of the totn_string variable.

We have written the output of the concat() method to the web browser console log, for demonstration purposes, to show what the concat() method returns.

The following will be output to the web browser console log:

TechOnTheNet
Tech

As you can see, the concat() method returned the concatenated string value of 'TechOnTheNet'. This is the concatenation of the string 'Tech' + 'On' + 'The' + 'Net'.

The value of the original totn_string variable has not changed and is still equal to 'Tech'.

Concatenating with an Empty String Variable

You can use the concat() method with an empty string variable to concatenate primitive string values.

For example:

var totn_string = '';

console.log(totn_string.concat('Tech','On','The','Net'));

The following will be output to the web browser console log:

TechOnTheNet

By declaring a variable called totn_string as an empty string or '', you can invoke the String concat() method to concatenate primitive string values together. This would be equivalent to the following:

console.log(''.concat('Tech','On','The','Net'));

The + operator is another way to concatenate string values together:

console.log('Tech' + 'On' + 'The' + 'Net');

The + operator allows you to concatenate strings without the need for the String object and the String concat() method.