What characters are valid for JavaScript variable names?


In this article, we will learn what characters are valid for JavaScript variable names.

We use variables to save values. First, we have to define the variable, and then we can assign a value to it. We can use the variable name to access the variable in the code. With a variable name, we can reassign its value.

As you adhere to a few principles, variable names are quite versatile.

Rules

  • A letter, dollar sign($), or underscore (_) must make up the first character. A number cannot be the initial character.

  • Any letter, number, or underscore can complete the variable name. You cannot use some characters, such as spaces, symbols, and punctuation.

  • Names of variables are case-sensitive.

  • The name of the variable can be of any limit as per your need.

  • The name of a variable cannot contain a reserved word in JavaScript.

Keywords that are not allowed as a variable name

break, case, catch, continue, debugger, default, delete, do, else, finally, for,

function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var,

void, while, and with

Reserved keywords for future by ES5 in normal mode

class, const, enum, export, extends,
import, and super.

Reserved keywords for future by ES5 in strict mode

implements, interface, let, package,
private, protected, public, static, and yield

Not reserved words by ES5

int, byte, char, goto, long, final, float,

short, double, native, throws, boolean, abstract, volatile, transient, and synchronized

Correct Variables

test
TEST
$test
_test
_123test
test_value123$
testValue

Valid variables according to ECMA Script

var π;//pi 
var ಠ_ಠ; 
var ლ_ಠ益ಠ_ლ; 
var λ;//lamda
var \u006C\u006F\u006C\u0077\u0061\u0074; 
var foo\u200Cbar;
var 〱〱; var price_99̶_89;
var Ꙭൽↈⴱ;
var ᱹ;//dot
var τ; // tau
var ℏ;// Dirac’s constant
var ε;//Euler's constant
var Ѵ;//Square root
(function() { var NaN;//Valid inside function }());

Incorrect Variables

class – Should not use JavaScript keywords.
a bc – Should not contain space.
#abc – Should not start with special characters.
2abc – Should not start with a number.

Invalid variables according to ECMA Script

var NaN;//In the global scope

Users can follow the syntax below to check the correctness of a variable name.

function isValidVariable(name) {
   try {
      Function('var ' + name);
   } catch (e) {
      return false;
   }
   return true;
}

To check whether a variable name is valid or not, we can use the function given in this syntax box.

Suggestions

  • It is wise to select a case and stick with it throughout the code. Example: the camel case. The code appears neat and professional.

  • Use multiple words when naming your variable. This will confirm the accuracy of your variable's name.

  • Avoid very short variable names.

  • Use a meaningful variable name. For example, OrderNum or Order_Num.

Example 1

In this example, we check the validity of a JavaScript variable with the syntax given above. We give a static variable name as the input to the function. Here it is a correct variable name.

<html> <body> <h2>Check the validity of a variable name<i></h2> <div id = "btnWrap"> <p>Click the button</p> <button onclick = "isValidVariable()"> Click Me</button> </div> <div id = "dispDom1"></div> <div id = "dispDom2"></div> <script> var varNamBtn = document.getElementById("btnWrap"); var varNamOutput1 = document.getElementById("dispDom1"); var varNamOutput2 = document.getElementById("dispDom2"); var varNamStr = ""; function isValidVariable() { var cbk = function(name) { try { Function('var ' + name); } catch (e) { varNamOutput1.innerHTML = "<b>" + name + "</b> is an invalid variable name"; return false; } varNamOutput2.innerHTML = "<b>" + name + "</b> is a valid variable name"; return true; }; cbk('test'); cbk('#test'); } </script> </body> </html>

Example 2

In this example, we check the validity of a JavaScript variable with the syntax given above. We give dynamic variable names as the input from the user to the function.

<html> <body> <h2>Checking the validity of Varible Name</h2> <div id = "btnWrap"> <p>Enter a variable name and click the button</p> <input id = "varNamUsrInp" type = "text" placeholder = "Enter a variable name"/> <button onclick = "isValidUserVariable()">Click Me</button> </div> <div id = "dispDom1"></div> <script> var varNamUsrBtn = document.getElementById("btnWrap"); var varNamUsrOutput1 = document.getElementById("dispDom1"); var varNamUsrInput = document.getElementById("varNamUsrInp"); var varNamUsrStr = ""; function isValidUserVariable() { var name = varNamUsrInput.value; var cbk = function(name) { try { Function('var ' + name); } catch (e) { varNamUsrOutput1.innerHTML = "<b>" + name + "</b> is an invalid variable name"; return false; } varNamUsrOutput1.innerHTML = "<b>" + name + "</b> is a valid variable name"; return true; }; cbk(name); } </script> </body> </html>

In this tutorial, we have seen the valid characters for JavaScript variables. We suggest following the naming conventions to code better.

Updated on: 31-Oct-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements