Comp 101 Concatenation


What if we run into a situation where we want to put two strings together?

We can use the "+", or plus sign, math operator to "add" two strings together. However, it's best to think about this using the technical term concatenation rather than adding.

For example, if we had two strings made up of digits like so:

let x = "123";
let y = "456";
let z = x+y;

z evaluates to be "123456", not 579 as it would if we were adding together number values. This is because the second string is concatenated onto the end of the first.

For that reason, x+y and y+x do not result in the same string. Continuing our example from earlier, y+x would evaluate to "456123".

Another great example is when we want to concatenate a string and a number! Let's look at a code snippet:

let age = await promptNumber("What's your age?");
print("Wow, actually? " + age + "? That's pretty old!");

This way, we can see something printed like, "Wow, actually? 19? That's pretty old!"

How would you concatenate the following variables to print the phrase "Not as old as you!"
let words1 = "old as ";
let word = "you!";
let words2 = "Not as ";