Which one is string interpolation?


#1

Hi,
I can't find the explanation for "String Interpolation" anywhere else on the internet.
Using a + sign to combine strings is every where else on the internet called "String Concatenation"!!

Now following both snippets result in the same output.
Which one is "String Interpolation" (if any) and which one is "String Concatenation"?

var favoriteAnimal = "Horse";
console.log("My favorite animal: "  +  favoriteAnimal);

var favoriteAnimal2 = "Horse";
console.log("My favorite animal2: " , favoriteAnimal2);

Thanks


#2

In a sense, going back to before we actually had string interpolation, we could have referred to concatenation as one and the same thing. We are incorporating a variable into a string, whether for immediate output or to store. The value is interpolated in string form.

Today the definition given is much more precise, owing that we now actually do have a way to embed variables in a string literal without resorting to concatenation.

>> favoriteAnimal = 'dog'
>> favAnimal = `My favorite animal: ${favoriteAnimal}`
<- "My favorite animal: dog"

Don't try it in the lesson, or if you do, be prepared for possible SCT error. Your browser already supports it, though.. (The above is the FF web console.)

Now as to the second example using a comma, that is just a list separator. .log() takes a comma separated list and outputs with single space between values. While it concatenates (or appears to) on the screen, all that is really happening is serial output with no line breaks (newlines).


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.