Skip to content

Instantly share code, notes, and snippets.

@junerockwell
Last active August 5, 2024 18:27
Show Gist options
  • Save junerockwell/644848efbb34d7753c9e8c0faeaab5aa to your computer and use it in GitHub Desktop.
Save junerockwell/644848efbb34d7753c9e8c0faeaab5aa to your computer and use it in GitHub Desktop.
Make strings using JavaScript concatenation
const hello = "hello";
const world = "world";
const name = "John";
const numberOne = 1; // number not a string
// String concatenation is making a new string combining other strings
// sometimes using variables.
const newSentence1 = hello + " " + world;
console.log('newSentence1 = ' + newSentence1);
const newSentence2 = hello + " " + world + "hey " + name;
console.log('newSentence2 = ' + newSentence2);
const newSentence3 = hello + " " + world + "number is " + numberOne;
// The numberOne variable contains a number, it doesn't become
// a string. But in newSentence3 variable, it becomes part of a string.
console.log('newSentence3 = ' + newSentence3);
const newSentence4 = `${hello} ${world}`;
console.log('newSentence4 = ' + newSentence4);
/* newSentence5 and newSentence6 do the exact same thing */
const newSentence5 = "#" + hello; // Outputs #hello using the original JS concatenation way
const newSentence6 = `#${hello}` // Outputs #hello but need backticks
console.log('newSentence5 = ' + newSentence5);
console.log('newSentence6 = ' + newSentence6);

String Concatenation in JavaScript

The examples are combining string and number data types with and/or without variables. This is called concatenation.

The original, "old school," way is using + (plus). The latest way for the last few years is using backticks with ${variableName}.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment