Uncaught syntaxerror invalid or unexpected token ошибка

Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:

for var i = 1; i < 10; i++ {
<span style="font-weight: 400;">  // какой-то код</span>
<span style="font-weight: 400;">}</span>

После запуска в браузере цикл падает с ошибкой:

❌ Uncaught SyntaxError: Unexpected token ‘var’

Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.

Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.

Что делать с ошибкой Uncaught SyntaxError: Unexpected token

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

Интерпретатор обязательно показывает номер строки, где произошла ошибка Uncaught SyntaxError: Unexpected token

Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:

Строка с ошибкой Uncaught SyntaxError: Unexpected token

По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:

  • Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i<10; i++) {}
  • Посмотрите на предыдущие команды. Если там не закрыта скобка или кавычка, интерпретатор может ругаться на код немного позднее.

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

Каждый из этих фрагментов кода даст ошибку Uncaught SyntaxError: Unexpected token. Попробуйте это исправить.

if (a==b) then  {}
function nearby(number, today, oneday, threeday) {
  if (user_today == today + 1 || user_today == today - 1)
    (user_oneday == oneday + 1 || user_oneday == oneday - 1)
      && (user_threeday == threeday + 1 || user_threeday == threeday - 1)
  return true
  
  else
     return false
}
var a = prompt('Зимой и летом одним цветом');
if (a == 'ель'); {
  alert("верно");
} else {
  alert("неверно");
}
alert(end);

I have a razor syntax like this:

   foreach(var item in model)
 {
<td><a href ="#"  onclick="Getinfo(@item.email);" >6/16/2016 2:02:29 AM</a>  </td>
 }

My javascript that recieves the request goes like this:

<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
    function Getinfo(elem) {
        var email = document.getElementById(elem).innerHTML;
    }
</script>

When clicking on the href link, I get the following error in the console of the browser:

«Uncaught SyntaxError: Invalid or unexpected token»,

and this part is underlined:

    **</a>  </td>**

I am a beginner so I get stuck in syntax a lot. If it is that then please help me out.

Satpal's user avatar

Satpal

132k13 gold badges158 silver badges167 bronze badges

asked Jun 16, 2016 at 11:50

Himaan Singh's user avatar

You should pass @item.email in quotes then it will be treated as string argument

<td><a href ="#"  onclick="Getinfo('@item.email');" >6/16/2016 2:02:29 AM</a>  </td>

Otherwise, it is treated as variable thus error is generated.

answered Jun 16, 2016 at 11:53

Satpal's user avatar

SatpalSatpal

132k13 gold badges158 silver badges167 bronze badges

1

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(‘) to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

answered Jan 5, 2019 at 13:20

Iman Bahrampour's user avatar

Iman BahrampourIman Bahrampour

6,0802 gold badges41 silver badges64 bronze badges

I also had an issue with multiline strings in this scenario. @Iman’s backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:

'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'

Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.

// This will work for the following:
// "hellonworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/n|<brs*/?>/gi, "r"));

answered Mar 26, 2019 at 11:14

cspete's user avatar

cspetecspete

1708 bronze badges

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

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

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 здесь.

I Include an external javascript file in an Html file, when I browse the Html file in a web browser, I meet the javascript error with the error message Uncaught SyntaxError: Invalid or unexpected token. This article will tell you how to fix it.

1. How To Reproduce The JavaScript Uncaught SyntaxError: Invalid Or Unexpected Token.

  1. The Html file name is test.html.
  2. In the test.html file, it imports an external javascript file test.js using the below code.
    <script type="text/javascript" src="test.js" ></script>
  3. Open the Html file test.html in the Google Chrome web browser.
  4. Right-click the web page in the web browser, then click the Inspect menu item in the popup menu list to open the web browser Inspector window.
  5. Click the Console tab on the web browser’s Inspector window.
  6. Then you can see the error message Uncaught SyntaxError: Invalid or unexpected token in the console output.

2. How To Fix The JavaScript Uncaught SyntaxError: Invalid Or Unexpected Token.

  1. The main reason for such error is because there are some unnormal characters in the javascript code that are not encoded in the correct charset.
  2. You just need to remove the javascript code in the error line, and to see whether the error disappears.
  3. Do not forget to refresh the test.html and the test.js file to make the change take effect.
  4. You can also copy the javascript code line that has the error occurs to the text editor such as Sublime Text.
  5. Then you can find the unnormal character in it and remove it to fix the error.
    <0x200b>​// Create a SnowFlakeApp instance when the window is loaded. 
    window.onload = new SnowFlakeApp();
  6. In the above example javascript code, the character <0x200b> is unnormal, remove it then you can fix the error.

Similar to other programming languages, JavaScript has its own syntax. The error “Uncaught SyntaxError: Unexpected token” shows that your code does not match the JavaScript syntax. It could be due to some typos in your code, a mistake when including a JavaScript file into HTML, or a wrong HTML in JavaScript code.

The reason for the error “Uncaught SyntaxError: Unexpected token”

JavaScript has its own syntax for literals, variables, operators, expressions, keywords, and comments. When running your code, the JavaScript runtime tries to parse the code based on the JavaScript syntax. When it cannot do, it throws an error “Uncaught SyntaxError: Unexpected token” with the position where the error occurs. Because it is a syntax error, there are many situations that can cause the error. Usually, it is due to you having an extra or missing a character or punctuation. Another reason is that you accidentally put some HTML code in your JavaScript code in the wrong way. You can reproduce the error with this example. You can easily see that I have an extra close bracket ‘)’, which causes the error.

Example code:

if (true)) {
    console.log('It is true');
} 

Output:

if (true)) {
         ^
SyntaxError: Unexpected token ')'

Example 1: Invalid syntax causes the error

There are many ways that your code has an invalid syntax that cause the error. Here I have an example in that I missed the open and close brackets of the if condition.

Example code:

let a = 1;
let b = 2;
let c = 3;

if (a + b == c) || (a == c) {
    console.log('a is ok');
} 

Output:

if (a + b == c) || (a == c) {
                ^^
SyntaxError: Unexpected token '||'

The error message will also show which is the unexpected token so that you can easily fix this error. You can also avoid invalid syntax in your code by using a suitable JavaScript snippet extension for your code editor, such as Visual Studio Code, Sublime Text, Atom,…

Example 2: Include a file that is not JavaScript to the script tag

Another common mistake that causes the error is including something that is not a valid JavaScript file in the script tag, maybe it is an HTML file.

Example code:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Page 1</title>
    <script src="index.html"></script>
</head>

<body>
    Some content!
</body>

</html>

Output:

Uncaught SyntaxError: Unexpected token '<' (at index.html:1:1)

When you load the HTML code above in your browser, you will get the error in the console. Of course, to fix this error, you need to specify the right path to the JavaScript file that you want to use.

Example 3: Invalid HTML code in JavaScript code

Sometimes, you have some HTML code in your JavaScript code, for example, when you want to set the innerHTML value for an element. Make sure you use your HTML code as a string by putting it in the quotes or you will get a syntax error.

Example code:

let message = document.getElementById("message");

// This's right
message.innerHTML = '<div>Message content</div>'; 

// This cause an error
message.innerHTML = <div>Message content</div>; 

Output:

message.innerHTML = <div>Message content</div>; 
                    ^
SyntaxError: Unexpected token '<'

Summary

In this tutorial, I have some examples to show you how to solve the error “Uncaught SyntaxError: Unexpected token” in JavaScript. You need to make sure your code has valid JavaScript syntax. Also, pay attention to having the right code when you use JavaScript with HTML.

Maybe you are interested in similar errors:

  • Uncaught SyntaxError Unexpected end of input
  • Unexpected token u in JSON at position 0
  • unexpected token o in json at position 1 error in js
  • Cannot read properties of undefined

Hello, I’m Joseph Stanley. My major is IT and I want to share programming languages to you. If you have difficulty with JavaScript, TypeScript, C#, Python, C, C++, Java, let’s follow my articles. They are helpful for you.


Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: JavaScript, TypeScript, C#, Python, C, C++, Java

Понравилась статья? Поделить с друзьями:
  • Uncar dll вернул код ошибки
  • Unb ошибка на стиральной машине leran
  • Unb ошибка на стиральной машине hisense
  • Unarc all вернул код ошибки 12
  • Unarac dll вернул код ошибки 1