feat(curriculum): Add interactive examples to What Is String Concatenation, and How Can You Concatenate Strings with Variables (#63213)

This commit is contained in:
Clarence Bakosi 2025-10-29 00:07:45 +01:00 committed by GitHub
parent 918f14173b
commit 9b39665c97
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-is-string-concatenation
---
# --description--
# --interactive--
In JavaScript, working with text is an essential part of coding, and often, you'll need to combine or join pieces of text together. This process is called string concatenation.
@ -15,39 +15,53 @@ The `+` operator is one of the simplest and most frequently used methods to conc
Here's an example:
:::interactive_editor
```js
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // John Doe
let fullName = firstName + " " + lastName;
console.log(fullName); // John Doe
```
:::
In this example, we used the `+` operator to concatenate the `firstName` and `lastName` variables along with a space (`" "`) to create the full name.
One disadvantage of using the `+` operator for string concatenation is that it can lead to spacing issues if you don't carefully manage the spacing between the concatenated strings.
Here is an example where a space is missing:
:::interactive_editor
```js
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + lastName; // "JohnDoe"
let fullName = firstName + lastName;
console.log(fullName); // "JohnDoe"
```
:::
Whenever you use the `+` operator to concatenate strings, it is important to double check for any potential spacing issues.
If you need to add or append to an existing string, then you can use the `+=` operator. This is helpful when you want to build upon a string by adding more text to it over time.
Here's an example of appending one string to another using the `+=` operator:
:::interactive_editor
```js
let greeting = 'Hello';
greeting += ', John!';
// greeting is now the string Hello, John!
console.log(greeting); // "Hello, John!"
```
:::
It is important to remember that strings are immutable which means once a string is created you can not alter it.
In this case, the original string of `Hello` is not modified. Instead, greeting now references the new string of `Hello, John!`
@ -62,13 +76,18 @@ In future lessons, we will dive much deeper into how functions, objects, and met
Here's an example of using the `concat()` method to join two strings together:
:::interactive_editor
```js
let str1 = 'Hello';
let str2 = 'World';
let result = str1.concat(' ', str2); // Hello World
let result = str1.concat(' ', str2);
console.log(result); // Hello World
```
:::
In this example, we use the `concat()` method to join `str1`, a space (`' '`), and `str2` into a single string.
To conclude, `+` operator is best for simple concatenation, especially when you need to combine a few strings or variables.