jaredrada
jaredrada

Reputation: 1150

whats wrong with this ternary operator?

I have an object menuNames which should maintain a list of menu items. If menuNames already has the slug, increment the value, if it doesnt contain the slug, set the value equal to 1. I'm doing this to track unique names. I want to end up with something like:

menuNames: {
    home: 1,
    products: 10,
    contact: 1
}

this doesnt work (this would be contained in a loop going through each slug):

menuNames[slug] = (menuNames.hasOwnProperty(slug) ? menuNames[slug]++ : 1);
//this sets every value to 1

but this does work (this would be contained in a loop going through each slug):

if(menuNames.hasOwnProperty(slug)) {
    menuNames[slug]++;
} else {
    menuNames[slug] = 1;
}

Upvotes: 5

Views: 1665

Answers (3)

insertusernamehere
insertusernamehere

Reputation: 23570

I guess it could work like this:

menuNames[slug] = (menuNames.hasOwnProperty(slug) ? ++menuNames[slug] : 1);

Upvotes: 3

Halcyon
Halcyon

Reputation: 57709

As the other answers say the problem is in the post increment.

Another way to write it is:

menuNames[slug] += (some_bool ? 1 : 0);

++ is very sensitive to bugs. Try to write it as a += statement.


if menuNames[slug] can be undefined, write it as:

menuNames[slug] = 0;
if (some_bool) {
    menuNames[slug] += 1;
}

This is (in my opinion) the clearest way to write an initialization/counter loop.

If you like one-liners you'll cringe, but if you like bug free code you'll be happy to see this.

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227180

menuNames[slug]++ increments the value, but also returns the original value.

You are doing menuNames[slug] =, so the value is set back to the original value after being incremented.

To fix it, just simply do:

menuNames[slug] = (menuNames.hasOwnProperty(slug) ? menuNames[slug]+1 : 1);

Or:

(menuNames.hasOwnProperty(slug) ? menuNames[slug]++ : menuNames[slug] = 1);

Upvotes: 8

Related Questions