Search code examples
javascriptjavascript-objectsreserved-words

Javascript reserved word and object


I'm making a dictionary of words, so there are 1,000,000+ words. The problem comes when I need to store the word constructor. I know this is a reserved word in javascript, but I need to add it to the dictionary.

var dictionary = {} 
console.log(dictionary ['word_1']) 
//undefined, this is good
console.log(dictionary ['word_2']) 
//undefined, this is good
console.log(dictionary ['constructor']) 
//[Function: Object] 
// this cause initialization code to break

How can I fix this? I could muck with the it like key=key+"_" but that seems bad. Is there anything else I can do?


Solution

  • Instead of using a JS object, you could use the built-in Map type which uses strings/symbols as keys and does not conflict with any existing properties.

    Replace var dictionary = {} with var dictionary = new Map()