Open In App

Why JavaScript Variable Starts with a Dollar Sign ?

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, it is common to see variables that start with a dollar sign ($). This convention is not required by the language, but it is often used by developers to indicate that a variable is a jQuery object or to distinguish it from other types of variables.

In JavaScript, variable names can only contain letters, numbers, and underscores (_), and they cannot start with a number. However, the dollar sign ($) is a valid character to use in a variable name. Therefore, a variable that starts with a dollar sign is a valid identifier in JavaScript.

Indicating a variable in Javascript: One of the main reasons why developers use a dollar sign to start a variable name is to indicate a variable is Javascript.

 

Here’s an example of a variable in Javascript:

var $myDiv = 'GeeksforGeeks';

In this example, the variable $myDiv is a variable that stores a string value in Javascript.

Distinguishing from other types of variables: Another reason why developers might use a dollar sign to start a variable name is to distinguish it from other types of variables. For example, a variable that represents a string might be named “myString”, while a variable that represents another string might be named “$myString”. This convention helps to make the code more readable and easier to understand.

Here’s an example of a variable that uses a dollar sign to distinguish it from other types of variables:

var $message = "GeeksforGeeks";
var message = 'Hello, world!';

In this example, the variable $message is a variable storing a string value. The variable message is a string that contains the text “Hello, world!”. By using a dollar sign to start the variable name, the developer can quickly identify that the ‘$message’ is a different variable from the ‘message’ variable.

Example 1: Here is an example of using a dollar sign to indicate a  variable in Javascript:

Javascript




let $myStr = 'GeeksforGeeks'
console.log($myStr)


Output

GeeksforGeeks

Example 2: Here is an example of using a dollar sign to distinguish a variable from other types of variables in a JavaScript file:

Javascript




var $myDiv = "GeeksforGeeks";
var myDiv = 'This is a string.';
console.log($myDiv)
console.log(myDiv)


Output

GeeksforGeeks
This is a string.

In conclusion, using a dollar sign to start a variable name in JavaScript is a convention that is often used to indicate that a variable is a jQuery object or to distinguish it from other types of variables. While it is not required by the language, it can help make the code more readable and easier to understand, especially when working with complex JavaScript applications.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads