Concatenation: Combining Texts

Concatenation is the process of combining two or more strings into one. In JavaScript, you can concatenate strings using the + operator.

For example, let's say we have two strings:

Loading Code . . .

We can concatenate them to create a full name like this:

Loading Code . . .

Note that we added a space between the first and last name by including a space between the quotes.

Adding strings to variables

You can also concatenate strings to variables using the += operator.

For example, let's say we have a variable greeting that contains the string "Hello":

Loading Code . . .

We can add a string to the variable using the += operator:

Loading Code . . .

The += operator is a shorthand for greeting = greeting + ' world'. The result of this operation is that the string " world" is added to the end of the greeting variable, resulting in the final string "Hello world".

Notice that we are using the let keyword to declare the greeting variable. This is because we are reassigning the variable to a new value. So, we are mutating the variable.

The .concat() method

Another way to concatenate strings is to use the concat() method. The concat() method is used on a string and takes one or more strings as arguments. It returns a new string that is the result of concatenating the arguments to the string on which the method was called.

For example, let's say we have two strings:

Loading Code . . .

We can concatenate them to create a full name like this:

Loading Code . . .

Code Challenge

Create a function called concatenation that takes two strings as arguments and returns the concatenation of the two strings.

The strings will be separated by a dash (-).

Ex: concatenation('Hello', 'World') should return "Hello-World".

Loading...

© 2024 - ®Mewters