Open In App

$ in JavaScript

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a dollar ($) sign is not considered a built-in operator or a special symbol. The dollar sign ( $ ) is just another character that can be used in variable names. It is just like any other letter that can be used as the first or subsequent character in a variable name.

Using $ as an Identifier

The dollar ($) sign in JavaScript can be used as an identifier which means it can be used to simply identify an object in the same way that a variable or name does. It can be used to identify any variable, function, object, property, or event.

Syntax:

function $(selector) {
return document.getElementById(selector);
}

Example: The below code implements the $ sign as the name of a function in JavaScript that selects elements.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>Using $ as Identifier</title>
</head>
 
<body>
    <div style="text-align: center;">
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <h2 id="output">
            Change the text of this element by <br/>
            clicking the below button.
        </h2><br/>
        <button id="btn">
            Change Text
        </button>
    </div>
    <script>
        function $(selector) {
            return document.getElementById(selector);
        }
        $('btn').addEventListener('click', ()=>{
            $('output').innerHTML = `Hey Geek, <br/>
            Welcome to GeeksforGeeks!!`
        })
    </script>
</body>
 
</html>


Output:

$GIF

Using $ in Template literals

The dollar ($) sign is also used in template literals. This method was introduced recently in the ECMAScript 2015 (also known as ES6 or ECMAScript 6) for a convenient way of string interpolation and multiline strings in JavaScript. The template literals are delimited using backticks (“), instead of single or double quotes. This method allows us to directly use an expression inside a string using placeholders, denoted by – ${expression}

Example: The below code explains the use of dollar ($) sign to access the values of variables in template literals.

Javascript




const name = 'GeeksforGeeks';
const desc = "A Computer Science Portal.";
 
console.log(`Company name: ${name}, Description: ${desc}`);


Output

Company name: GeeksforGeeks, Description: A Computer Science Portal.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads