Design & Download
Your JS Library
in Seconds!!!

Snippet: isValidVarName()

Written by Christopher West (cwest) on August 21, 2016.
Determine if the specified variable name is a valid one.
function isValidVarName(varName) {
  try {
    Function((varName + '').replace(/[\s\xA0,\/]|^$/g, '.'), '');
    return true;
  }
  catch (e) {
    return false;
  }
}

isValidVarName(...) API Documentation

Description

Determines if a string can be used as a variable name in JavaScript.

Parameters

  1. varName {string}:
    The string to be tested to see if it is a valid variable name.

Returns

Returns true if varName is a valid variable name, otherwise false is returned.

Example

console.log(YourJS.isValidVarName(''));          // -> false
console.log(YourJS.isValidVarName('i'));         // -> true
console.log(YourJS.isValidVarName('alpha'));     // -> true
console.log(YourJS.isValidVarName('get2'));      // -> true
console.log(YourJS.isValidVarName('undefined')); // -> true
console.log(YourJS.isValidVarName('null'));      // -> false
console.log(YourJS.isValidVarName('NaN'));       // -> true
console.log(YourJS.isValidVarName('3d'));        // -> false
console.log(YourJS.isValidVarName('_3d'));       // -> true
console.log(YourJS.isValidVarName('_3dæ'));      // -> true
console.log(YourJS.isValidVarName('d,a'));       // -> false
console.log(YourJS.isValidVarName('d a'));       // -> false