Syntaxe javascript

Syntaxe javascript
0

#1

I saw a lot of code like this:
It’s test ternaire I know that.
But first the test don’t have parenteses(why not), but then the sign = assign a variable then compare it?
Can you explain better?
counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;

EDIT
It’a possible this is similar ?
var cts = counts[item] = counts[item];
(cts >= 1) ? counts[item] + 1 : 1;

EDIT 2
it’a more:
counts[item] = (counts[item] >= 1) ? counts[item] + 1 : 1;
It’s messy without the parenteses :frowning:
I hate when I saw a code like this and uncomment…
I was reading left to right and break on this.

Thanks


#2

#3

It is called Conditional (ternary) Operator.

It is a shorter way to write if ... else statements.


#4

I know is a ternary operator, but my question is not this.
we have an assignment in the code i gave.
Thanks


#5

Best to read it like this:
counts[item] = (counts[item] >= 1 ? counts[item] + 1 : 1);

It checks if counts[item] is bigger than or equal to 1. If it is, increment counts[item] by 1. If it isn’t, set counts[item] to 1.
You could also write it like this:

if (counts[item] >= 1) {
    counts[item] += 1;
} else {
    counts[item] = 1;
}

#6

yeah, I need parentheses :slight_smile:
It’s only possible in javascript without parenteses, Java or PHP that’s doesn’t work ?