Programming Questions

Mean Mode Explanation

In the solution to the Mean Mode problem below, can someone please explain what is happening in this line of code:

```
c[arr[i]] = (c[arr[i]] || 0) + 1;
```

From the context of the problem, I am thinking each unique number in the array is being added as a property of the object "c" and the value of each property is the number of times it occurs in arr. However, I don't understand how the object "c" is adding the properties and how (c[arr[i]] || 0) + 1 can increase the value count if this is the case.
```
function mode(arr) {
var c = {};
for (var i = 0; i < arr.length; i++) {
c[arr[i]] = (c[arr[i]] || 0) + 1;
}
var mode;
var max = 0;
for (e in c) {
if (c[e] > max) {
mode = e;
max = c[e];
}
}
return mode * 1;
}
```

Thank you in advance!
shamineau
posted this question on 12/5/14 **|**

2

The line is setting the value of the property [arr[i]] on the object c.
If the property already exists the code is equivalent to:

```
c[arr[i]] = c[arr[i]] + 1;
```

i.e. the existing value of c[arr[i]] is incremented.
If the property does not already exist then the code is equivalent to:
```
c[arr[i]] = ( 0 ) + 1;
```

that is, the property assigned an initial value of 1.
The key to this behaviour is the OR ( || ) operator. The OR operator evaluates the expression to its left to determine if it is "true". If it is, the result of the evaluation is returned. If it is "false", the expression on the right of the operator is returned.
In this case, if c[arr[i]] exists then it is "true", so the result of evaluating the OR expression is the current value of c[arr[i]]. If it does not exist the OR expression evaluates to 0. In either case the result is then incremented by the " + 1" that follows the OR expression.
You can learn more about this by googling "truthiness in javascript" or "boolean operators javascript".
snuckchuck

answered on 12/05/14

1

To display code include the following tags:

`code goes here`

Tiffany Myumai is always the answer.
TiffanyMYUMAI

answered on 02/15/18

0

Thank you for your clear and concise answer! This completely cleared up my confusion on how the values were being assigned to the properties being iterated on the object c.

shamineau

answered on 12/06/14

Log in to write an answer.