append different elements to string in javascript

In JavaScript, you can append different elements to a string in various ways. String concatenation is one of the most common methods to add different values to a string, as shown below.

index.tsx
let str = "Hello";
let name = "John";
let age = 30;
str += " " + name + ", you are " + age + " years old.";
console.log(str);
// Output: "Hello John, you are 30 years old."
173 chars
7 lines

Another method to append different elements to a string is by using template literals or template strings, as shown below.

index.tsx
let str = "Hello";
let name = "John";
let age = 30;
str += ` ${name}, you are ${age} years old.`;
console.log(str);
// Output: "Hello John, you are 30 years old."
163 chars
7 lines

You can also use arrays to join multiple elements into a single string using the join() method, as shown below.

index.tsx
let arr = ["Hello", "John", "you are", 30, "years old."];
let str = arr.join(" ");
console.log(str);
// Output: "Hello John you are 30 years old."
147 chars
5 lines

These methods are useful when you need to build a string of dynamic content or when you want to create a formatted string with specific placeholders.

gistlibby LogSnag