// Template Literals in javascript
// Longhand:
let firstName = "Chetan", lastName = "Nada";
const welcome = 'Hello my name is ' + firstName + ' ' + lastName;
console.log(welcome); //Hello my name is Chetan Nada
// Shorthand:
const welcome_ = `Hello my name is ${firstName} ${lastName}`;
console.log(welcome_); //Hello my name is Chetan Nada
//Must use backticks, `, in order to work.
let a = 5;
let b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
//Output:
//Fifteen is 15 and not 20.
/** A template literal produces a new string literal type by concatenating
the contents. When a union is used in the interpolated position, the
type is the set of every possible string literal that could be
represented by each union member: */
type Taste = "Delicious" | "Spicy";
type Food = "Pizza" | "Meat";
type Menu = `${Taste | Food}`;
// Menu will now be one of the following:
// 'DeliciousPizza' | 'DeliciousMeat' | 'SpicyPizza' | 'SpicyMeat'
If you are gonna copy and paste answers from MDN... you should AT LEAST
check the page hedaer to see what topic you are copying. That way you don't
post a porno graphic where a 3-D graphic belongs.
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
tag`string text ${expression} string text`
// Untagged, these create strings:
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
// Tagged, this calls the function "tagFunction" with the template as the
// first argument and substitution values as subsequent arguments:
tagFunction`string text ${expression} string text`
// Untagged, these create strings:
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
// Re-usable template:
const templateFn = expression => `string text ${expression} string text`;
// Tagged, this calls the function "example" with the template as the
// first argument and substitution values as subsequent arguments:
example`string text ${expression} string text`
const str1 = 'This is a string';
// cannot use the same quotes
const str2 = 'A "quote" inside a string'; // valid code
const str3 = 'A 'quote' inside a string'; // Error
const str4 = "Another 'quote' inside a string"; // valid code
const str5 = "Another "quote" inside a string"; // Error
let fruits = {
banana: 1,
orange: 5
};
let sentence = `We have ${banana} Banana/s and ${orange} orange/s!`;
console.log(sentence); // We have 1 Banana/s and 5 orange/s!