1

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.

AppSensei
  • 8,270
  • 22
  • 71
  • 99

3 Answers3

3

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).

Dekel
  • 60,707
  • 10
  • 101
  • 129
3

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.

LearningEveryday
  • 584
  • 1
  • 3
  • 13
2

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
    }

});
Manuel Abascal
  • 5,616
  • 5
  • 35
  • 68