Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get "Invalid left-hand side in assignment"?

There is code:

function search(list, q){
  var result = {};
  for(let id in list)(
    (!q.id    || (id == q.id)) &&
    (!q.name  || (list[id].name.search(q.name) > -1)) &&
    result[id] = list[id]
  );

  return result;
}

I get this error:

Uncaught ReferenceError: Invalid left-hand side in assignment    script.js:4

Why "&&" is wrong?

like image 854
Turar Abu Avatar asked Dec 01 '17 03:12

Turar Abu


People also ask

Which is an invalid assignment operator?

A single “=” sign instead of “==” or “===” is an Invalid assignment. Cause of the error: There may be a misunderstanding between the assignment operator and a comparison operator.

What is assignment error in JS?

The "Assignment to constant variable" error occurs when trying to reassign or redeclare a variable declared using the const keyword. When a variable is declared using const , it can't be reassigned or redeclared.


1 Answers

The problem is that the assignment operator, =, is a low-precedence operator, so it's being interpreted in a way you don't expect. If you put that last expression in parentheses, it works:

  for(let id in list)(
    (!q.id    || (id == q.id)) &&
    (!q.name  || (list[id].name.search(q.name) > -1)) &&
    (result[id] = list[id])
  );
like image 72
Pointy Avatar answered Sep 24 '22 02:09

Pointy