freq
is an object:
Working with objects - JavaScript | MDN[
^]
Objects have properties. In Javascript, there are two ways to access properties. By name:
var x = someObj.myProperty;
someObj.otherProperty = 42;
Or by index:
var x = someObj['myProperty'];
someObj['otherProperty'] = 42;
Using the index is particularly useful if you don't know the name of the property until runtime.
If the specified property has not been defined, then it will return
undefined
. The
if
condition is making use of one of the uglier areas of Javascript - "truthy" and "falsy" values:
Truthy and Falsy: When All is Not Equal in JavaScript — SitePoint[
^]
This could be rewritten to make use of
the hasOwnProperty
method[
^], which might make the code slightly clearer, albeit more verbose:
if (freq.hasOwnProperty(character)){
If the specified property
doesn't exist, you initialize it to the number
1
.
Which is why, on subsequent iterations of the loop when the property
does exist, you are able to increment it.