node js variables in string
Certainly! Here's an example of using variables in a string in Node.js, with explanations for each step:
// Declare variables
let name = 'Alice';
let age = 30;
// Create a string using variables
let message = `Hello, my name is ${name} and I am ${age} years old.`;
// Output the string
console.log(message);
Explanation:
let name = 'Alice';
- Declares a variable namedname
and assigns the value'Alice'
to it.let age = 30;
- Declares a variable namedage
and assigns the value30
to it.javascript let message = `Hello, my name is ${name} and I am ${age} years old.`;
Creates a string variable
message
using template literals (enclosed in backticks`) that includes the values of
nameand
agevariables using
${}` syntax to embed variables within the string.console.log(message);
- Outputs the value stored in themessage
variable to the console, displaying the string with the values ofname
andage
embedded within it.