Search code examples
javascriptarraysquotes

javascript JSON and Array elements, help me understand the rule about quotes


When using a returned value to determine the number of an element in an array, does javascript throw quotes around it?

Example :

This tallys the number of times unique characters are used.

var uniques = {};

function charFreq(s)
{ 
    for(var i = 0; i < s.length; i++)
    {
       if(isNaN(uniques[s.charAt(i)])) uniques[s.charAt(i)] = 1;
       else uniques[s.charAt(i)] = uniques[s.charAt(i)] + 1;
    }

    return uniques;    
}

console.log(charFreq("ahasdsadhaeytyeyeyehahahdahsdhadhahhhhhhhhhha"));

It just seems funny that uniques[s.charAt(i)] works, and uniques[a] wont work (due to lack of quotes). uniques[a] will get you a nasty 'a is undefined'.


Solution

  • When you access a JavaScript object using the [] notation, you are using a string as a key in the object. You can also address properties using the . notation:

    uniques.a is the same as uniques['a']

    The reason you aren't adding quotes to the s.charAt(i) is that it returns a string, which is then used as the property to check on the uniques object.

    uniques[a] will create an error, because no variable with the name a has been defined.