Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert variables in JavaScript strings?

What's the best way to do insert variables in a string in JavaScript? I'm guessing it's not this:

var coordinates = "x: " + x + ", y: " + y;

In Java, Strings are immutable and doing something like the above would unnecessarily create and throw away Strings. Ruby is similar and has a nice way of doing the above:

coordinates = "x: #{x}, y: #{y}"

Does something similar exist for JavaScript?

like image 953
at. Avatar asked Sep 30 '13 22:09

at.


People also ask

How do you give a variable to a string in JavaScript?

To declare variables in JavaScript, you need to use the var, let, or const keyword. Whether it is a string or a number, use the var, let, or const keyword for its declaration. But for declaring a string variable we had to put the string inside double quotes or single quotes.

How do you add variables in JavaScript?

Basic JavaScript Addition Add numbers in JavaScript by placing a plus sign between them. You can also use the following syntax to perform addition: var x+=y; The "+=" operator tells JavaScript to add the variable on the right side of the operator to the variable on the left.

Which one allows us to insert variables into the string?

This example uses the “ s string interpolator,” which lets you embed variables inside a string, where they're replaced by their values.


1 Answers

Introduced in ES6 as "template strings"

MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

const name = "Nick"
const greeting = `Hello ${name}`  // "Hello Nick"
like image 139
Nick Brady Avatar answered Sep 17 '22 15:09

Nick Brady