Unable to update Object property number (counter) for counting alphabet

I am new to JavaScript, and I am trying to count number of each alphabet in the bigLettersArr. I made a for loop to go through each element in bigLettersArr and update the counter, but somehow it doesn’t work. Again, all I am trying to do is to update alphabet object counter to get number of each leters.

Also, I think there might be much smarter way to do this, I looked up other methods for array, but was not able to find and come up with better code.

Here’s my code. Thank for reading this!

const bigLettersArr = [ "X","E","Q","M","L","L","L","B","X","C","A","F",
                        "X","W","B","W","A","F","D","Z","B","C","L","F",
                        "M","E","B","E","A","M","L","L","B","G","L","G",
                        "H","F","H","G","M","A","F","B","B","C","G","F",
                        "H","Z","B","L","L","H","J","L"]

//made an empty array with all alphabet A-Z 
const alphabet = {
                    'A': 0, 'B': 0, 'C': 0, 'D': 0, ... 'Z':0
                 }
             //Count how many each alphabet in the array.   
                for(let letter in bigLettersArr){
                    let targetLetter = bigLettersArr[letter]
                    // console.log(targetLetter)
                    alphabet.targetLetter += 1
                }


            console.log(alphabet)

Answer

Arrays are iterables in JS. so you can simply use for..of loop here

You should use for..in loop with objects and for..of with arrays

The for…in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.-MDN

The for…of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.-MDN

You can also use forEach instead of for..of as:

bigLettersArr.forEach(letter => alphabet[letter] += 1);

const bigLettersArr = ["X", "E", "Q", "M", "L", "L", "L", "B", "X", "C", "A", "F",
    "X", "W", "B", "W", "A", "F", "D", "Z", "B", "C", "L", "F",
    "M", "E", "B", "E", "A", "M", "L", "L", "B", "G", "L", "G",
    "H", "F", "H", "G", "M", "A", "F", "B", "B", "C", "G", "F",
    "H", "Z", "B", "L", "L", "H", "J", "L"]

const alphabet = Array
.from( { length: 26 }, ( _, i ) => String.fromCharCode( i + 65 ))
.reduce( ( acc, curr ) => ( ( acc[curr] = 0 ), acc ), {} );

for ( let letter of bigLettersArr ) {
    alphabet[letter] += 1
}

console.log( alphabet )
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }