0

So I'm following some tutorials on Udemy & on the whole they have been excellent except now there is a new instructor for the part I'm on now who isn't as descriptive on the inner workings of the functions.

The current example is a function that counts how many iterations of vowels there are within said string.

function vowelCount(str){
    var splitArr = str.toLowerCase().split("");
    var obj = {};
    var vowels = "aeiou";

    splitArr.forEach(function(letter){

        if(vowels.indexOf(letter) !== -1){
            if(obj[letter]){
                obj[letter]++;
            } else{
                obj[letter] = 1;
            }
        }
    });

}

vowelCount("abcdefghij")

The part that I'm personally stumped on is if(obj[letter])

In my mind the obj variable is empty and anything within the [] in this case is a reference to an index, and I don't understand what it is the if statement is checking I also don't really understand the syntax that follows of obj[letter].

Any enlightenment on this would be highly appreciated.

Munerz
  • 1,052
  • 1
  • 13
  • 26

1 Answers1

2

That's doing this:

  1. Evaluating obj[letter] (more on this part in this question's answers):
    • Evaluating letter to get its current value (for instance, "a")
    • Evaluating obj to get its current value (the object)
    • Getting the value of the property named "a" (for instance) on the object; if the property doesn't exist, the result of that will be the value undefined
  2. Branching into the if if the value from Step 1 is truthy

A truthy value is any value that isn't falsy. The falsy values are undefined, null, 0, "", NaN, and of course, false.

Basically what that code is doing is seeing if obj already has a property for the letter and, if so, incrementing its value; if not, it's setting its value to 1.

Don't generalize that pattern too much, though. It works here because the property's value will never be 0 or "" or similar (the values being stored start at 1 and only increase). But in other situations, if you need to see if a property exists on an object but its value may be one of those falsy values, use either obj.hasOwnProperty(letter) (to check if the property exists on the object itself, rather than its prototype), letter in obj if you want to check the object and its prototype chain, or if you want to be paranoid about hasOwnProperty being redefined use Object.prototype.hasOwnProperty.call(obj, letter). :-)

But this "falsy" check is very useful when you know the property will either not be there, or have a truthy value.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875