Reputation: 8400
I get the expected result here.
var modeObj = {};
array.forEach(num => {
if (!modeObj[num])
modeObj[num] = 0;
modeObj[num]++;
});
I get an empty result here.
var modeObj = {};
array.forEach(num => {
if (!modeObj[num]) {
modeObj[num] = 0;
}else {
modeObj[num]++;
}
});
How is the above code different from the one below? I'm missing some concept in the if condition.
Upvotes: 1
Views: 48
Reputation: 584
The first code if condition does not have {}
. Hence only the first line is executed and the line modeObj[num]++;
is executed no matter what the result of the if condition is.
In the second code, you have added an else.
Upvotes: 3
Reputation: 62536
When you have if/else
- the line inside the else
block will only gets evaluated when the value of the if
is false.
In your first example - the second line will run every time, whether the if is valid or not.
If you don't have brackets - only the next line (after the if
) is evaluated.
Your first example is actually the following:
var modeObj = {};
array.forEach(num => {
if (!modeObj[num]) {
modeObj[num] = 0;
}
modeObj[num]++;
});
As you can see - the modeObj[num]++;
will get evaluated every time (not only when the if
is true).
Upvotes: 3
Reputation: 6312
You're increasing modeObj[num]++
outside if
part of the conditional & the second code snippet. It should be like so instead:
var modeObj = {};
array.forEach(num => {
if (!modeObj[num]) {
modeObj[num] = 0;
modeObj[num]++;
} else {
// do something
}
});
Upvotes: 2