I want to check if a property exists in my object or not, If it exists I want to add a number to it and if it doesn’t I want to create a property and set the value to 1.
I did everything and i used optional chaining and logical assignment but there is an error it says:
Uncaught SyntaxError: Invalid left-hand side expression in postfix operation
can you say whats the problem?
here is the code:
const scores = {};
for (const player of Object.values(game.scored)) {
scores?.[player]++ && scores[player] = 1;
}
note: game.scored contains 4 names;
i did my best, i could do it with ternary operator and it worked but i want to know why it doesn’t work with optional chaining and logical assignment
3
Answers
You can’t assign to an optionally chained expression; they can’t appear on the "left-hand side" of an assignment.
This would require something like this to work:
How is this supposed to work when
a
is null? You’d effectively be producing the statementundefined = 1
.In your case you’re expecting this to work:
What happens if
scores
isnull
? You end up withundefined = undefined + 1
, neither the left-hand or right-hand side of that assignment make sense.Note that, the whole thing is written incorrectly, and it makes no sense to write
scores?.[player]
when you’ve just assignedscores = {}
two lines up.scores?.[player]
checks whetherscores
is null, not whetherscores[player]
is null.You’re trying to test whether the key
player
is already in the objectscores
, which is here: How to check if object property exists with a variable holding the property name?here, (scores[player] ?? 0) checks if the left expression is null, and if so it returns the one on the right, otherwise it’ll return the one on the left. Therefore scores[player] will be assigned scores[player] + 1 when it already exists, and be created and assigned a 1 when it doesn’t. HIH
In addition to the problems already pointed out with
scores?.[player]++
, you have an operator precedence problem that will produce a similar error, even if if you fixed your current error.x && x = 1
is evaluated as(x && x) == 1
, notx && (x = 1)
. If you fix your code, ie usingscores.[player]++ && scores[player] = 1
, you will still be producing an invalid left-hand operand of an assignment operator, resulting in a similar error to the one you have now:You should add a pair of parentheses like this: