views:

59

answers:

3

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'.

+1  A: 

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.

gnarf
+1  A: 

In the first version -- uniques[s.charAt(i)] -- you're doing the lookup using an expression. JavaScript evaluates the expression -- s.charAt(i) -- and uses the evaluated value (maybe a) to perform the lookup in the uniques map.

In the second version -- uniques[a] -- you want to do the lookup using the literal character a, but unless you wrap it in quotes then JavaScript treats the a as an expression rather than a literal. When it tries to evaluate the "expression" then you get an error.

So the rule is: character/string literals need quotes; expressions that evaluate to characters/strings don't.

LukeH
+1  A: 

This is how Javascript evaluates the expression between [] like uniques[s.charAt(i)] which is of the type MemberExpression[ Expression ] :

  1. Let propertyNameReference be the result of evaluating Expression.
  2. Let propertyNameValue be GetValue(propertyNameReference).
  3. Let propertyNameString be ToString(propertyNameValue).

So in the 3rd step it is converting the property name into a string.

Regards, Satyajit

Satyajit