Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 322
jaredrada Avatar asked Feb 08 '13 16:02

jaredrada


3 Answers

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);
like image 192
Rocket Hazmat Avatar answered Oct 16 '22 11:10

Rocket Hazmat


I guess it could work like this:

menuNames[slug] = (menuNames.hasOwnProperty(slug) ? ++menuNames[slug] : 1);
like image 32
insertusernamehere Avatar answered Oct 16 '22 11:10

insertusernamehere


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.

like image 2
Halcyon Avatar answered Oct 16 '22 11:10

Halcyon