Dynamic variable property names

suggest change

prompt and alert are browser-only. This example stores the property name in a variable, asks the user which word to look up, and reads that property from dictionary. An unknown word yields undefined.

var dictionary = {
    lettuce: 'a veggie',
    banana: 'a fruit',
    tomato: 'it depends on who you ask',
    apple: 'a fruit',
    Apple: 'Steve Jobs rocks!' // properties are case-sensitive
}

var word = prompt('What word would you like to look up today?')
var definition = dictionary[word]
alert(word + '\n\n' + definition)

Note how we are using [] bracket notation to look at the variable named word; if we were to use the traditional . notation, then it would take the value literally, hence:

console.log(dictionary.word)  // doesn't work because word is taken literally and dictionary has no field named `word`
console.log(dictionary.apple) // it works! because apple is taken literally

console.log(dictionary[word]) // it works! because word is a variable, and the user perfectly typed in one of the words from our dictionary when prompted
console.log(dictionary[apple]) // error! apple is not defined (as a variable)

A literal name works in brackets too: dictionary['apple']. See Properties with special characters or reserved words.

You can also set dynamic properties with the bracket syntax:

var property="test";
var obj = {
  [property]: 1
};

console.log(obj.test);//1

It does the same as:

var property="test";
var obj={};
obj[property]=1;

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents