AppSensei
AppSensei

Reputation: 8400

Difference between these codes in the if block

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

Answers (3)

LearningEveryday
LearningEveryday

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

Dekel
Dekel

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

Manuel Abascal
Manuel Abascal

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

Related Questions