Can I concatenate strings with other data types? Can I interpolate strings with other data types?

Question

Can I concatenate strings with other data types? Can I interpolate strings with other data types?

Answer

Definitely! However, remember that if one of the values/variables/expressions being concatenated or interpolated is not a string, it will be converted to a string before the concatenation/interpolation takes place. Also if using string interpolation with template literals, expressions will be evaluated before any conversion to a string and before being interpolated.

Example:

const a = 9;
const b = 4;
const c = 7;

console.log('This string is using concatenation ' + a + b + c); //Here the variables a, b, and c will be converted to strings then concatenated. `This string is using concatenation 947` will be logged to the console.

console.log(`This string is using string interpolation ${a}${b}${c}`); //Here the variables a, b, and c will be converted to strings and then interpolated. `This string is using string interpolation 947` will be logged to the console.

console.log(`This string is using string interpolation with an expression ${a + b + c}`); //Here the expression is evaluated first, the expression is converted into a string, and then interpolated. `This string is using string interpolation with an expression 20` will be logged to the console.
6 Likes

Thank you

console.log(This string is using string interpolation ${a}${b}${c});

nice info. Thank you very much <3

Thank you for this info. Especially for String interpolation with an expression.