Almost every website uses JavaScript. It is an easy and handy language to learn. Beginners can implement JavaScript efficiently with some prior knowledge of programming. There are several special symbols in JavaScript. Here, we shall learn about the dollar sign ($) and its uses.
What does $ mean in JavaScript?
$ acts as an identifier in JavaScript. $ identifies a variable, function, object, or others just as a name would in the real world.
Identifiers are the names given to any variable, functions, classes, and objects by the developers or programmers. There are some rules for declaring an identifier, the identifier's name must begin with either a:
- Letter (A to Z or a to z)
- Dollar symbol($)
- Underscore(_)
What is the role of $ in JavaScript?
In JavaScript we can use $ sign for embeding and evaluating an expression inside a string. It allows multi-line string and string interpolation features. Here is an example:
Code:
<html>
<head>
<title>$ in JavaScript</title>
</head>
<body>
<p id="joy"></p> <!-- The id attribute defines the html element-->
<script>
let string = `The sum of 10 + 9 is ${10+9}`; //eveluates the result inside the string and return the result.
document.getElementById("joy").innerHTML = string;
</script>
</body>
</html>
Output:
Here is another example using $ that embeds a value from a javaScript variable in a string.
Code:
<html>
<head>
<title>$ in JavaScript</title>
</head>
<body>
<h2>$ in JavaScript</h2>
<p id="joy"></p>
<script>
let myage=20;
let string = `I am ${myage} years old`; //eveluates the result inside the string and return the result.
document.getElementById("joy").innerHTML = string;
</script>
</body>
</html>
Output:
Conclusion:
We hope this tutorial has given a clear idea about the role of the dollar sign ($) in JavaScript. It is a special symbol in JavaScript that acts as an identifier. It also has other significant uses like using ($) for embedding an expression inside a string and embedding a value from a JavaScript variable into a string.