Search code examples
javascriptjavascript-objects

Understanding JavaScript code for counting occurrences of each character in a string


I need some help understanding the following code:

function AllChars(str) {

var myObj = {};
for(var i=0;i<str.length;i++){
if(myObj[str[i]]===undefined){
  myObj[str[i]]=0;
}
myObj[str[i]]++;

}
return myObj;

}

AllChars('banana');

Output
{b: 1, a: 3, n: 2}

It basically returns an object where each key is a character in the given string. Here is the question:

The for loop runs from 0 to the length of the string. Then the if function checks str[0] which is the first element should be the letter 'b' then this letter 'b' is added to the myObj[str[i]]] this is what I don't understand why would myObj[str[0]] be undefined when it was 'b' in str[0]?


Solution

  • 1. The AllChars function

    Your function takes a string as parameter and loops through the string (str)... And for each loop, it retrieves the next character in the string.

    1. Now, if the character have not yet been encountered before, it is added to the "empty" object as a key, of which value is 0. This way, it create a counter of occurrences of that character in the string str.

    2. Otherwise (if it (that character: str[i]) has already been encountered), needless to index it again in myObj.

    At the end of each loop, the counter (of the current character) is incremented.

    At the end of the function, myObj is returned.

    2. AllChars('banana');

    This line call the function AllChars defined above with the string 'banana' as parameter.

    3. The output

    The output suggest to me that the code is being ran from a javascript console, which output the value of myObj returned from AllChars('banana');

    It is either the browser console or the node.js console.

    So the output is representative of that (key => value) object.

    {b: 1, a: 3, n: 2}