What is String.concat() in JavaScript?

The concat() method joins multiple strings, with a source string , nd returns a new string.

Syntax

string.concat(...strings);

Example

let source = "I love";
let joinedString = source.concat("Educative.io");
console.log(joinedString);
// joining multiple string
joinedString= source.concat(" ", "Educative.io", " and ", "JavaScript Jeep");
console.log(joinedString);

When we don’t pass in an argument, a copy of the source string is returned.

let source = "Educative";
let joinedString = source.concat();
console.log("Calling concat without argument. Joined string = ", joinedString);

If the argument passed in is not a string, then it is internally converted to a string.

console.log('calling "".concat({}) -->',"".concat({}) );
console.log('calling "".concat([]) -->',"".concat([]) );
console.log('calling "".concat(null) -->',"".concat(null) );
console.log('calling "".concat(4, 5) -->',"".concat(4, 5) );
console.log('calling "".concat(a => a) -->',"".concat(a => a) );

Instead of concat(), we can use the assignment operator (this is the recommended method).

let source = "I";
let joinedString = source + " Love " + "Educative.io";
console.log(joinedString);

Free Resources