Ошибка invalid assignment left hand side

Ситуация: вы пишете код, который обрабатывает нажатия на клавиши для управления в игре. Вы вспоминаете, что нужно сделать отдельную функцию для проверки на попадание в цель. Для этого вы хотите сравнить текущие координаты с координатами цели — если они совпадают, то есть попадание. В результате получается такой код:

function collision () {
if(x = target.x && y = target.y) {
alert(«Столкновение!»);
}
};

Но при запуске игра падает с ошибкой:

❌ ReferenceError: Invalid left-hand side in assignment

Что случилось: браузер видит условный оператор if и хочет выполнить сравнения в скобках. Если равенство выполняется, то условие истинно и можно выполнить команду вывода на экран. Но вместо сравнения браузер встречает оператор присваивания, понимает, что ему тут не место, и останавливает программу.

Чтобы ошибки не было, нужно использовать не один знак равенства, а два. Один — присваивание, два — сравнение:

function collision () {
if(x == target.x && y == target.y) {
alert(«Столкновение!»);
}
};

Когда встречается: когда мы делаем что-то не то с левой частью выражения — присваиваем вместо сравнения или перенаправляем вывод в переменную, которая не предназначена для такого. Ещё такая ошибка бывает, когда что-то пытаются присвоить ключевому слову this — оно хоть и похоже на переменную по поведению, но присваивать ему новое значение так нельзя.

Как исправить ошибку ReferenceError: Invalid left-hand side in assignment

Скорее всего, вы используете присваивание вместо сравнения. Это частая ошибка у новичков, потому что в математике знак «=» означает именно равенство.

Если дело не в этом, то вот вопросы, которые помогут вам с поиском ошибки:

  • можно ли вообще делать с этой переменной то, что вы делаете;
  • нужен ли отдельный модуль или компонент для выполнения этой команды и подключён ли он;
  • правильно ли вы используете эту команду или оператор — на всякий случай уточните и загляните в справочник.

Попробуйте сами

if (Math.PI = 3 || Math.PI = 4) { 
  console.log('Потрачено!');
}
var str = 'Привет, '
+= 'это журнал '
+= 'Код!';

Задание со звёздочкой: есть такой фрагмент кода на странице

<input type=»text» id=»number»><br>

Enter exponent:<br>

<input type=»text» id=»degree»><br><br><br>

<button id=»button»>Result</button>

<input type=»text» id=»result»>

И есть такой скрипт, который при нажатии на кнопку падает с нашей ошибкой:

var button = document.getElementById('button');
button.addEventListener('click', math);
 
function math(a,b){
    var a = document.getElementById('number').value;
    var b = document.getElementById('degree').value;
    var result = Math.pow(a,b);
    document.getElementById('result') = result;
}

Common reasons for the error:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42 instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === — What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence. In particular we are looking for && (precedence 6) and = (precedence 3).

Let’s put braces in the expression according to priority — && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6:

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two) can’t be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy).

Note that if you’d use braces to match perceived priority surrounding each «equality» with braces you get no errors. Obviously that also producing different result than you’d expect — changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial &&:

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}

For even more details on the error and other cases when it can happen — see specification:

Assignment

LeftHandSideExpression = AssignmentExpression

Throw a SyntaxError exception if the following conditions are all true:

IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

… function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference…

Время на прочтение
5 мин

Количество просмотров 398K

JavaScript может быть кошмаром при отладке: некоторые ошибки, которые он выдает, могут быть очень трудны для понимания с первого взгляда, и выдаваемые номера строк также не всегда полезны. Разве не было бы полезно иметь список, глядя на который, можно понять смысл ошибок и как исправить их? Вот он!

Ниже представлен список странных ошибок в JavaScript. Разные браузеры могут выдавать разные сообщения об одинаковых ошибках, поэтому приведено несколько примеров там, где возможно.

Как читать ошибки?

Перед самим списком, давайте быстро взглянем на структуру сообщения об ошибке. Понимание структуры помогает понимать ошибки, и вы получите меньше проблем, если наткнетесь на ошибки, не представленные в этом списке.

Типичная ошибка из Chrome выглядит так:

Uncaught TypeError: undefined is not a function

Структура ошибки следующая:

  1. Uncaught TypeError: эта часть сообщения обычно не особо полезна. Uncaught значит, что ошибка не была перехвачена в catch, а TypeError — это название ошибки.
  2. undefined is not a function: это та самая часть про ошибку. В случае с сообщениями об ошибках, читать их нужно прямо буквально. Например, в этом случае, она значит то, что код попытался использовать значение undefined как функцию.

Другие webkit-браузеры, такие как Safari, выдают ошибки примерно в таком же формате, как и Chrome. Ошибки из Firefox похожи, но не всегда включают в себя первую часть, и последние версии Internet Explorer также выдают более простые ошибки, но в этом случае проще — не всегда значит лучше.

Теперь к самим ошибкам.

Uncaught TypeError: undefined is not a function

Связанные ошибки: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected

Возникает при попытке вызова значения как функции, когда значение функцией не является. Например:

var foo = undefined;
foo();

Эта ошибка обычно возникает, если вы пытаетесь вызвать функцию для объекта, но опечатались в названии.

var x = document.getElementByID('foo');

Несуществующие свойства объекта по-умолчанию имеют значение undefined, что приводит к этой ошибке.

Другие вариации, такие как “number is not a function” возникают при попытке вызвать число, как будто оно является функцией.

Как исправить ошибку: убедитесь в корректности имени функции. Для этой ошибки, номер строки обычно указывает в правильное место.

Uncaught ReferenceError: Invalid left-hand side in assignment

Связанные ошибки: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’

Вызвано попыткой присвоить значение тому, чему невозможно присвоить значение.

Наиболее частый пример этой ошибки — это условие в if:

if(doSomething() = 'somevalue')

В этом примере программист случайно использовал один знак равенства вместо двух. Выражение “left-hand side in assignment” относится к левой части знака равенства, а, как можно видеть в данном примере, левая часть содержит что-то, чему нельзя присвоить значение, что и приводит к ошибке.

Как исправить ошибку: убедитесь, что вы не пытаетесь присвоить значение результату функции или ключевому слову this.

Uncaught TypeError: Converting circular structure to JSON

Связанные ошибки: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported

Всегда вызвано циклической ссылкой в объекте, которая потом передается в JSON.stringify.

var a = { };
var b = { a: a };
a.b = b;
JSON.stringify(a);

Так как a и b в примере выше имеют ссылки друг на друга, результирующий объект не может быть приведен к JSON.

Как исправить ошибку: удалите циклические ссылки, как в примере выше, из всех объектов, которые вы хотите сконвертировать в JSON.

Unexpected token ;

Связанные ошибки: Expected ), missing ) after argument list

Интерпретатор JavaScript что-то ожидал, но не обнаружил там этого. Обычно вызвано пропущенными фигурными, круглыми или квадратными скобками.

Токен в данной ошибке может быть разным — может быть написано “Unexpected token ]”, “Expected {” или что-то еще.

Как исправить ошибку: иногда номер строки не указывает на правильное местоположение, что затрудняет исправление ошибки.

Ошибка с [ ] { } ( ) обычно вызвано несовпадающей парой. Проверьте, все ли ваши скобки имеют закрывающую пару. В этом случае, номер строки обычно указывает на что-то другое, а не на проблемный символ.

Unexpected / связано с регулярными выражениями. Номер строки для данного случая обычно правильный.

Unexpected; обычно вызвано символом; внутри литерала объекта или массива, или списка аргументов вызова функции. Номер строки обычно также будет верным для данного случая.

Uncaught SyntaxError: Unexpected token ILLEGAL

Связанные ошибки: Unterminated String Literal, Invalid Line Terminator

В строковом литерале пропущена закрывающая кавычка.

Как исправить ошибку: убедитесь, что все строки имеют правильные закрывающие кавычки.

Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference

Попытка прочитать null или undefined так, как будто это объект. Например:

var someVal = null;
console.log(someVal.foo);

Как исправить ошибку: обычно вызвано опечатками. Проверьте, все ли переменные, использованные рядом со строкой, указывающей на ошибку, правильно названы.

Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference

Попытка записать null или undefined так, как будто это объект. Например:

var someVal = null;
someVal.foo = 1;

Как исправить ошибку: это тоже обычно вызвано ошибками. Проверьте имена переменных рядом со строкой, указывающей на ошибку.

Uncaught RangeError: Maximum call stack size exceeded

Связанные ошибки: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow

Обычно вызвано неправильно программной логикой, что приводит к бесконечному вызову рекурсивной функции.

Как исправить ошибку: проверьте рекурсивные функции на ошибки, которые могут вынудить их делать рекурсивные вызовы вечно.

Uncaught URIError: URI malformed

Связанные ошибки: URIError: malformed URI sequence

Вызвано некорректным вызовом decodeURIComponent.

Как исправить ошибку: убедитесь, что вызовы decodeURIComponent на строке ошибки получают корректные входные данные.

XMLHttpRequest cannot load some/url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource

Связанные ошибки: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at some/url

Эта проблема всегда связана с использованием XMLHttpRequest.

Как исправить ошибку: убедитесь в корректности запрашиваемого URL и в том, что он удовлетворяет same-origin policy. Хороший способ найти проблемный код — посмотреть на URL в сообщении ошибки и найти его в своём коде.

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Связанные ошибки: InvalidStateError, DOMException code 11

Означает то, что код вызвал функцию, которую нельзя было вызывать в текущем состоянии. Обычно связано c XMLHttpRequest при попытке вызвать на нём функции до его готовности.

var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Some-Header', 'val');

В данном случае вы получите ошибку потому, что функция setRequestHeader может быть вызвана только после вызова xhr.open.

Как исправить ошибку: посмотрите на код в строке, указывающей на ошибку, и убедитесь, что он вызывается в правильный момент или добавляет нужные вызовы до этого (как с xhr.open).

Заключение

JavaScript содержит в себе одни из самых бесполезных ошибок, которые я когда-либо видел, за исключением печально известной Expected T_PAAMAYIM_NEKUDOTAYIM в PHP. Большая ознакомленность с ошибками привносит больше ясности. Современные браузеры тоже помогают, так как больше не выдают абсолютно бесполезные ошибки, как это было раньше.

Какие самые непонятные ошибки вы встречали? Делитесь своими наблюдениями в комментариях.

P.S. Этот перевод можно улучшить, отправив PR здесь.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single “=” sign instead of “==” or “===” is an Invalid assignment.

    Message:

    ReferenceError: invalid assignment left-hand side

    Error Type:

    ReferenceError

    Cause of the error: There may be a misunderstanding between the assignment operator and a comparison operator.

    Basic Example of ReferenceError – Invalid assignment left-hand side, run the code and check the console

    Example 1:

    Javascript

    if (Math.PI = 10 || Math.PI = 5) {

        console.log("Inside Loop");

    }

    Output:

    ReferenceError: Invalid left-hand side in assignment

    Example 1: In this example, “=” operator is misused as “==”, So the error occurred.

    HTML

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <title>Document</title>

    </head>

    <body style="text-align: center;">

        <h1 style="color: green;">

            GeeksforGeeks

        </h1>

        <p>

            JavaScript ReferenceError -

            Invalid assignment left-hand side

        </p>

        <button onclick="Geeks();">

            click here

        </button>

        <p id="GFG_DOWN"></p>

        <script>

            let el_down = document.getElementById("GFG_DOWN");

            function Geeks() {

                try {

                    if ((Math.PI = 10 || Math.PI = 5)) {

                        document.write("Inside Loop");

                    }

                    el_down.innerHTML =

                        "'Invalid assignment left-hand side'" +

                        " error has not occurred";

                } catch (e) {

                    el_down.innerHTML =

                        "'Invalid assignment left-hand side'" +

                        "error has occurred";

                }

            }

        </script>

    </body>

    </html>

    Output:

    JavaScript ReferenceError - Invalid assignment left-hand side

    Example 2: In this example, the + operator is used with the declaration, So the error has not occurred.

    HTML

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <title>Invalid assignment left-hand side</title>

    </head>

    <body style="text-align:center;">

        <h1 style="color:green;">

            GeeksforGeeks

        </h1>

        <p>

            JavaScript ReferenceError -

            Invalid assignment left-hand side

        </p>

        <button onclick="Geeks();">

            click here

        </button>

        <p id="GFG_DOWN">

        </p>

        <script>

            let el_down = document.getElementById("GFG_DOWN");

            function Geeks() {

                try {

                    let str = 'Hello, '

                        + 'Geeks'; // Error Here

                    el_down.innerHTML =

                        "'Invalid assignment left-hand side'" +

                        "error has not occurred";

                } catch (e) {

                    el_down.innerHTML =

                        "'Invalid assignment left-hand side'" +

                        "error has occurred";

                }

            }

        </script>

    </body>

    </html>

    Output: 

    JavaScript ReferenceError - Invalid assignment left-hand side

    Last Updated :
    22 May, 2023

    Like Article

    Save Article

    The “Invalid left-hand side in assignment” in JavaScript is a syntax error that often occurs in comparing values, such as using the “=” sign to compare. This article will give examples of everyday situations and how to fix them.

    This is a very common syntax error. There are many causes of errors, such as wrong comparison signs, using “=” to compare two values, and not creating a variable to receive a value from the function. Here are examples of some errors.

    Using the wrong comparison sign

    “Invalid left-hand side in assignment” is an error caused by misspelled operator when comparing two values.

    Example:

    // Wrong comparison sign
    if (5 =< 10 ) {
    	console.log("test");
    }

    Output:

    Uncaught SyntaxError: Invalid left-hand side in assignment

    Using “=” to compare two values

    This error also happens because instead of using “===”, you use “=” to compare.

    Example:

    // Wrong comparison sign
    if (10 = 10) {
    	console.log("test");
    }

    Output:

    Uncaught SyntaxError: Invalid left-hand side in assignment

    Not creating a variable to receive a value from the function

    This case leaves the wrong position of the variable.

    Example:

    const count = (first, second) => {console.log("test");}
    
    // Wrong position
    count(10, 10) = total;

    Output:

    Uncaught SyntaxError: Invalid left-hand side in assignment

    Do not use square brackets when accessing object properties

    For properties like this, we need to use square brackets.

    Example:

    const car = {};
    
    // Error because of a dot 
    car.full-name = "Honda";

    Output:

    Uncaught SyntaxError: Invalid left-hand side in assignment

    Solution for the error “Invalid left-hand side in assignment” in JavaScript

    Use the correct operator

    We need to pay attention to the comparison signs in expressions.

    // Use "<=" instead of "=<"
    if (5 <= 10 ) {
    	console.log("test");
    }
    // Use === instead of =
    if (10 === 10) {
    	console.log("test");
    }

    Pay attention to the position on either side of the “=”

    To get the value of a function, we need to create a variable to the left of the “=” sign.

    const count = (first, second) => {
    	console.log("test");
    };
    
    // This is the correct position
    let total = count(10, 10);

    Use square brackets when accessing properties

    For properties of objects with two or more words, we use square brackets.

    const car = {};
    
    // Use square brackets for properties like this
    car["full-name"] = "Honda";

    Summary

    The article has given some examples that lead to the error “Invalid left-hand side in assignment” in JavaScript. These are just syntax errors, pay attention to the process of writing code, and we will avoid such errors. We hope you can fix it quickly through this article. Good luck to you!

    Maybe you are interested:

    • TypeError: Assignment to Constant Variable in JavaScript
    • Element type is invalid, expected a string (for built in components) or a class/function but got – How to solve?
    • RangeError: Invalid time value in JavaScript

    Example 2: In this example, the + operator is used with the declaration, So the error has not occurred.

    HTML

    <!DOCTYPE html>

    <html lang="en">

    <head>

        <title>Invalid assignment left-hand side</title>

    </head>

    <body style="text-align:center;">

        <h1 style="color:green;">

            GeeksforGeeks

        </h1>

        <p>

            JavaScript ReferenceError -

            Invalid assignment left-hand side

        </p>

        <button onclick="Geeks();">

            click here

        </button>

        <p id="GFG_DOWN">

        </p>

        <script>

            let el_down = document.getElementById("GFG_DOWN");

            function Geeks() {

                try {

                    let str = 'Hello, '

                        + 'Geeks'; // Error Here

                    el_down.innerHTML =

                        "'Invalid assignment left-hand side'" +

                        "error has not occurred";

                } catch (e) {

                    el_down.innerHTML =

                        "'Invalid assignment left-hand side'" +

                        "error has occurred";

                }

            }

        </script>

    </body>

    </html>

    Output: 

    JavaScript ReferenceError - Invalid assignment left-hand side

    Last Updated :
    22 May, 2023

    Like Article

    Save Article

    The “Invalid left-hand side in assignment” in JavaScript is a syntax error that often occurs in comparing values, such as using the “=” sign to compare. This article will give examples of everyday situations and how to fix them.

    This is a very common syntax error. There are many causes of errors, such as wrong comparison signs, using “=” to compare two values, and not creating a variable to receive a value from the function. Here are examples of some errors.

    Using the wrong comparison sign

    “Invalid left-hand side in assignment” is an error caused by misspelled operator when comparing two values.

    Example:

    // Wrong comparison sign
    if (5 =< 10 ) {
    	console.log("test");
    }

    Output:

    Uncaught SyntaxError: Invalid left-hand side in assignment

    Using “=” to compare two values

    This error also happens because instead of using “===”, you use “=” to compare.

    Example:

    // Wrong comparison sign
    if (10 = 10) {
    	console.log("test");
    }

    Output:

    Uncaught SyntaxError: Invalid left-hand side in assignment

    Not creating a variable to receive a value from the function

    This case leaves the wrong position of the variable.

    Example:

    const count = (first, second) => {console.log("test");}
    
    // Wrong position
    count(10, 10) = total;

    Output:

    Uncaught SyntaxError: Invalid left-hand side in assignment

    Do not use square brackets when accessing object properties

    For properties like this, we need to use square brackets.

    Example:

    const car = {};
    
    // Error because of a dot 
    car.full-name = "Honda";

    Output:

    Uncaught SyntaxError: Invalid left-hand side in assignment

    Solution for the error “Invalid left-hand side in assignment” in JavaScript

    Use the correct operator

    We need to pay attention to the comparison signs in expressions.

    // Use "<=" instead of "=<"
    if (5 <= 10 ) {
    	console.log("test");
    }
    // Use === instead of =
    if (10 === 10) {
    	console.log("test");
    }

    Pay attention to the position on either side of the “=”

    To get the value of a function, we need to create a variable to the left of the “=” sign.

    const count = (first, second) => {
    	console.log("test");
    };
    
    // This is the correct position
    let total = count(10, 10);

    Use square brackets when accessing properties

    For properties of objects with two or more words, we use square brackets.

    const car = {};
    
    // Use square brackets for properties like this
    car["full-name"] = "Honda";

    Summary

    The article has given some examples that lead to the error “Invalid left-hand side in assignment” in JavaScript. These are just syntax errors, pay attention to the process of writing code, and we will avoid such errors. We hope you can fix it quickly through this article. Good luck to you!

    Maybe you are interested:

    • TypeError: Assignment to Constant Variable in JavaScript
    • Element type is invalid, expected a string (for built in components) or a class/function but got – How to solve?
    • RangeError: Invalid time value in JavaScript

    Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).

    Понравилась статья? Поделить с друзьями:
  • Ошибка invalid argument что это
  • Ошибка invalid argument to date encode
  • Ошибка invalid algorithm specified 0x80090008
  • Ошибка internal error 0x05 config error
  • Ошибка install failed older sdk