Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

What characters are valid for JavaScript variable names ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, we will see the valid variable names in JavaScript. The valid variable names can contain letters (both uppercase and lowercase), numbers, underscores, and dollar signs. However, the variable names can not begin with numbers.

Some examples of valid variable names:

var Geeks;
var Geeks_for_Geeks;
var $Geeks;
var _Geeks;
var Geeks123;

Some examples of invalid variable names:

var Geeks-for-Geeks;  // Hyphens not allowed
var 123Geeks;  // Can not start with numbers
var Geeks for Geeks;  // Spaces not allowed

Note: The variable name can not be the same as JavaScript keywords, such as if, else, var, function, etc.

Rules for variable name:

  • Spaces are not allowed in variable names.
  • Hyphens are not allowed in variable names.
  • Only letters, numbers, underscores, and dollar signs are permitted in variable names.
  • Case matters when it comes to variable names.
  • Variable name always starts with a letter (alphabet), underscore (_), or a dollar sign ($), i.e. any other special characters not allowed.
  • Reserved keywords are not allowed.

Example 1: In this example, we will declare some variables with their values and print their sum on the console.

Javascript




// Declare variable and assign value
let Geeks1 = 15;
let G$$ks = 20;
let Geeks_for_geeks = 30;
  
// Add numbers
const sum = Geeks1 + G$$ks + Geeks_for_geeks;
  
// Print the result
console.log(sum);


Output:

65

Example 2: In this example, we will declare some variables with values and print their values on the console.

Javascript




// Declare variables and assign value
let _Geeks1 = 15;
let $Geeks2 = 20;
let __Geeks3 = 30;
let $$Geeks4 = 40;
  
// Print the result
console.log(_Geeks1);
console.log($Geeks2);
console.log(__Geeks3);
console.log($$Geeks4);


Output:

15
20
30
40

Example 3: In this example, we will declare some invalid variables with their values and print them on the console, it displays some error message..

Javascript




// Declare variables and assign value
let @Geeks = 15;
let Geeks-for-Geeks = 30;
let Geeks for Geeks = 40;
  
// Print the result
console.log(@Geeks);
console.log(Geeks-for-Geeks);
console.log(Geeks for Geeks);


Output:

SyntaxError: Invalid or unexpected token

My Personal Notes arrow_drop_up
Last Updated : 23 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials