skip to Main Content

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


  1. 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:

    a?.foo = 1
    

    How is this supposed to work when a is null? You’d effectively be producing the statement undefined = 1.

    In your case you’re expecting this to work:

     scores?.[player] = scores?.[player] + 1
    

    What happens if scores is null? You end up with undefined = 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 assigned scores = {} two lines up. scores?.[player] checks whether scores is null, not whether scores[player] is null.

    You’re trying to test whether the key player is already in the object scores, which is here: How to check if object property exists with a variable holding the property name?

    Login or Signup to reply.
  2.   scores[player] = (scores[player] ?? 0) + 1;
    

    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

    Login or Signup to reply.
  3. 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, not x && (x = 1). If you fix your code, ie using scores.[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:

    Invalid left-hand side in assignment

    You should add a pair of parentheses like this:

    scores?.[player]++ && (scores[player] = 1);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search