Tuesday, 12 November 2024

String Concatenation in JavaScript: Using + and += Operators

What is String Concatenation?

String concatenation is the process of combining two or more strings together to form a new string. In JavaScript, you can concatenate strings using different methods.

 

How to Concatenate Strings in JavaScript

1. Using the + Operator

The simplest way to concatenate strings in JavaScript is by using the + operator.

 

Example

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: "John Doe"

 

In this example, the + operator combines firstName, a space " ", and lastName into the new string fullName.

 

2. Using the += Operator

The += operator is a shorthand way to concatenate strings. It adds the value on the right to the variable on the left and assigns the result back to the variable.

 

Example

 

let greeting = "Hello";
greeting += ", ";
greeting += "world!";
console.log(greeting); // Output: "Hello, world!"

 

In this example, greeting += ", " adds ", " to the original value "Hello", and then greeting += "world!" adds "world!" to the updated greeting.

 

concatStrings.js

 

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: "John Doe"

let greeting = "Hello";
greeting += ", ";
greeting += "world!";
console.log(greeting); // Output: "Hello, world!"

 

Output

John Doe
Hello, world!

 

In summary

1.   + Operator: Combines two or more strings directly.

2.   += Operator: Adds a string to an existing string variable and updates the variable with the new value.

 

Both methods are useful for different scenarios, depending on whether you want to build up a string gradually or combine strings all at once.

 


Previous                                                    Next                                                    Home

No comments:

Post a Comment