Address
304 North Cardinal St.
Dorchester Center, MA 02124
Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM
Address
304 North Cardinal St.
Dorchester Center, MA 02124
Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM
In JavaScript, a string is a data type that represents a sequence of characters. It can contain letters, numbers, symbols, and whitespace. Strings are commonly used to store and manipulate text-based data.
Template literals, also known as template strings, are a feature introduced in ECMAScript 2015 (ES6) to make working with strings in JavaScript more convenient. They allow for the embedding of expressions and variables inside a string, using a special syntax.
The syntax for creating a template literal is by using backticks (`) instead of single or double quotes. Here’s an example:
const name = “John”;
const age = 25;const message =
My name is ${name} and I'm ${age} years old.
;
console.log(message);
In this example, the template literal is enclosed between backticks. Inside the template literal, you can include placeholders ${expression}
which will be replaced with the evaluated value of the expression. In this case, the variables name
and age
are interpolated into the message
string.
+
operator, you can directly embed variables or expressions within the template string by enclosing them in ${}
. This makes the code more readable and avoids the need for explicit string conversions.${}
placeholders, and it will be evaluated and converted to a string. This allows for more dynamic and complex string generation.Template literals provide a flexible and concise way to work with strings in JavaScript, making code more readable and maintainable. They are widely used in modern JavaScript applications.
Here are a few examples of strings and template literals in JavaScript:
const greeting = "Hello, world!";
console.log(greeting);
Output:
Hello, world!
const firstName = "John";
const lastName = "Doe";
const fullName = `${firstName} ${lastName}`;
console.log(fullName);
Output:
John Doe
const poem = `Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.`;
console.log(poem);
Output:
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.
const num1 = 5;
const num2 = 7;
const result = `${num1} + ${num2} = ${num1 + num2}`;
console.log(result);
Output:
5 + 7 = 12
function greet(name) {
return `Hello, ${name}!`;
}
const userName = "Alice";
const greeting = greet(userName);
console.log(greeting);
Output:
Hello, Alice!
These examples demonstrate the usage of both simple strings and template literals, showcasing their ability to include variables, expressions, and even function calls within the string itself.