Skip to content Skip to sidebar Skip to footer

Determine If A Word Is A Reserved Javascript Identifier

Is it possible in Javascript to determine if a certain string is a reserved language keyword such as switch, if, function, etc.? What I would like to do is escaping reserved identi

Solution 1:

One option would be to do:

var reservedWord = false;
try {
  eval('var ' + wordToCheck + ' = 1');
} catch {
  reservedWord = true;
}

The only issue will be that this will give false positive for words that are invalid variable names but not reserved words.

As pointed out in the comments, this could be a security risk.

Solution 2:

I guess you could solve it using eval, but that seems like sort of a hack. I would go for just checking against all reserved words. Something like this:

var reservedWords = [
    'break',
    'case',
    ...
];

functionisReservedWord(str) {
    return !!~reservedWords.indexOf(str);
}

Here is a list of all reserved words: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Reserved_Words

Also, a problem with the eval-approach is that some browsers sometimes allows you to use some reserved words as identifiers.

Solution 3:

FYI, Some words throws error only in strict mode

ex: package

eval('var package = 1') // No error
'use strict'eval('var package = 1') // throws error

enter image description here

Post a Comment for "Determine If A Word Is A Reserved Javascript Identifier"