${} is a placeholder that is used in template literals. You can use any valid JavaScript expression such as variable, arithmetic operation, function call, and others inside ${}. The expression used inside ${} is executed at runtime, and its output is passed as a string to template literals.
For your better understanding of what is ${} in JavaScript, you must be familiar with template literals and string interpolation. In case you are not, then visit the following pages:
Instead of using string concatenation, you should use template literals to create the string that involves variables. To use variables inside template literals, you have to write the variable inside ${}. And when you execute the code, ${variable}
will be replaced with that variable's value.
//JavaScript program to calculate the area of circle. let radius = 4; let area = Math.PI*radius*radius; console.log(`The radius of circle is ${radius}.`); console.log(`The area of circle is ${area}.`);
Output
"The radius of circle is 4." "The area of circle is 50.26548245743669."
You can easily perform arithmetic operations inside template literals. All you have to do is write a valid arithmetic operation inside ${}. At runtime, the arithmetic operation is performed, and its result is returned as a string. Let's understand it by calculating the area and perimeter of a rectangle.
//JavaScript program to calculate the area and perimeter of rectangle. let length = 4; let width = 3; console.log(`The area of rectangle is ${length*width}.`); console.log(`The perimeter of rectangle is ${2*(length+width)}.`);
Output
"The area of rectangle is 12." "The perimeter of rectangle is 14."
From within the template literals, you have to call a function in a way you used to call the function. At runtime, ${functioncall()}
will be replaced by the result returned by the function.
//JavaScript program to calculate the area of square. function area(side){ return side*side; } let side = 9; console.log(`The area of square is ${area(side)}`);
Output
"The area of square is 81"