Меню

Invalid or unexpected token ошибка

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

131k13 gold badges156 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

131k13 gold badges156 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

5,8942 gold badges41 silver badges63 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

Когда встречается. Допустим, вы пишете цикл 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);

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

Syntax and runtime errors always produce error messages. Reading and
understanding error messages is a crucial first step in fixing these types of
bugs.

Error messages are your friends. This idea can seem foreign to new
programmers, because an error message is a signal that your program is broken.
When we are working with a broken program, we might feel frustrated, like we do
not fully understand the concepts at hand.

However, the reality is that all programmers, no matter how experienced,
regularly make simple mistakes. If you run your program and it produces an
error message, your first reaction should be, «Great! My program has an error,
but I have a helpful message to help me fix it.»

Let’s consider a small program with a couple of syntax errors.

Example

let name = Julie;
console.log("Hello, name);

While you can spot one or more errors just by looking at the code, let’s
examine the error messages produced.

6.3.1. A Syntax Error¶

Running the program at this stage results in the message:

/Users/chris/dev/sandbox/js/syntax.js:2
console.log("Hello, name);
            ^^^^^^^^^^^^^^

SyntaxError: Invalid or unexpected token
   at new Script (vm.js:85:7)
   at createScript (vm.js:266:10)
   at Object.runInThisContext (vm.js:314:10)
   at Module._compile (internal/modules/cjs/loader.js:698:28)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
   at Module.load (internal/modules/cjs/loader.js:630:32)
   at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
   at Function.Module._load (internal/modules/cjs/loader.js:562:3)
   at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
   at internal/main/run_main_module.js:21:11

While there is a lot of text in this message, the first few lines tell us
everything we need to know.

The first portion identifies where in our code the error exists:

console.log("Hello, name);
            ^^^^^^^^^^^^^^

For many simple syntax errors, we will quickly be able to spot the mistake once
JavaScript points out its location to us.

If knowing the location of the error isn’t enough, the next line provides more
information:

SyntaxError: Invalid or unexpected token

This line identifies that actual issue that JavaScript found. It makes it clear
that we are dealing with a SyntaxError, and it provides a message that
describes the issue.

If you are scratching your head at the message, «Invalid or unexpected token,»
don’t worry. Programming languages often report errors in ways that are not
always easy to decipher at first glance. However, a second look at the line in
question helps us make sense of this message.

console.log("Hello, name);
            ^^^^^^^^^^^^^^

JavaScript is telling us that in the area of "Hello, name); it encountered
an invalid token. Token is a fancy word that means a symbol, variable, or
other atomic element of a program. In this case, the invalid token is "Hello,
name);
. JavaScript sees the double-quote character and expects a string.
However, the string does not have a closing ", making it invalid.

Fixing this error gives us a program with correct syntax:

let name = Julie;
console.log("Hello", name);

Note

Error messages may differ depending on where you run your code. The same program run in a repl.it and Node.js on your computer will generate slightly different error messages. However, these differences are minor and generally unimportant. The main cause of the error will be reported in the same way.

6.3.2. Syntax Errors and Code Highlighting¶

Most code editors provide a feature known as syntax highlighting. Such
editors highlight different types of tokens in different ways. For example,
strings may be red, while variables may be green. This useful feature gives you
a quick, visual way to identify syntax errors.

For example, here is a screenshot of our flawed code taken within an editor at repl.it.

A screenshot with two lines of code. Syntax errors on each line cause highlighting to differ from what is expected. On line 1, the string "Julie" is green instead of red, because it is missing quotes. On line 2, the symbols ); are red instead of black, because the preceding string "Hello, World" doesn't have a closing double-quote.

Screenshot of a program with two syntax errors

Notice that the string Hello is colored red, while most of the symbols
(=, ;, ., and () are colored black. At the end of line 2,
however, the final ) and ; are both red rather than black. Since we
haven’t closed the string, the editor assumes that these two symbols are part
of
the string. Since we expect ); to be black in this editor, the
difference in color is a clue that something is wrong with our syntax.

6.3.3. A Runtime Error¶

Having fixed the syntax error, we can now run our program again. Doing so displays yet another error.

Hello
/Users/chris/dev/sandbox/js/syntax.js:1
let name = Julie;
         ^

ReferenceError: Julie is not defined
   at Object.<anonymous> (/Users/chris/dev/sandbox/js/syntax.js:1:74)
   at Module._compile (internal/modules/cjs/loader.js:738:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
   at Module.load (internal/modules/cjs/loader.js:630:32)
   at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
   at Function.Module._load (internal/modules/cjs/loader.js:562:3)
   at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
   at internal/main/run_main_module.js:21:11

We have a new error message, this time involving line 1 of our code. We didn’t see this error before because it is a runtime error. Due to the syntax error on line 2, the program stopped during the parsing phase. Even though the current error involves the line before the original syntax error, the syntax error still gets reported first.

Once again, we are told where the error occurs:

There appears to be an issue with the assignment statement. You might be able to see what it is, but let’s inspect the error message anyway. Doing so will help us understand JavaScript errors more generally.

The message is:

ReferenceError: Julie is not defined

The type of error is ReferenceError. If we search the web for «JS ReferenceError» then one of the first results is the MDN documentation for ReferenceError. No need to read the entire document, however. The first sentence on this page tells us what we need to know:

The ReferenceError object represents an error when a non-existent variable is referenced.

This information, along with the rest of the message, «Julie is not defined,» makes it clear what JavaScript is complaining about. The error message is saying, Hey, check your variables!

To us, we see that we forgot to enclose the string Julie in quotes, because we know that we intended to assign the variable name a string value. However, to JavaScript there is nothing in the program to indicate that Julie should be a string. In fact, JavaScript sees Julie as a variable. Since there is no such defined variable in our program, it returns a ReferenceError.

This is one of many examples when we, as humans, describe the same error slightly differently than JavaScript. Usually, neither description is better than the other. Humans and computers simply view information differently.

Сообщение

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"

Тип ошибки

Что пошло не так?

Вместо определённой конструкции языка было использовано что-то другое. Возможно, просто опечатка.

Примеры

Ожидаемое выражение

Недопустимыми являются, к примеру, запятые после элементов цепочки выражений.

for (let i = 0; i < 5,; ++i) {
  console.log(i);
}
// SyntaxError: expected expression, got ';'

Правильным вариантом будет убрать запятую или добавить ещё одно выражение:

for (let i = 0; i < 5; ++i) {
  console.log(i);
}

Недостаточно скобок

Иногда можно потерять скобки при использовании if:

function round(n, upperBound, lowerBound){
  if(n > upperBound) || (n < lowerBound){
    throw 'Число ' + String(n) + ' больше, чем ' + String(upperBound) + ', или меньше, чем ' + String(lowerBound);
  }else if(n < ((upperBound + lowerBound)/2)){
    return lowerBound;
  }else{
    return upperBound;
  }
} // SyntaxError: expected expression, got '||'

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

function round(n, upperBound, lowerBound){
  if((n > upperBound) || (n < lowerBound)){
    throw 'Число ' + String(n) + ' больше, чем ' + String(upperBound) + ', или меньше, чем ' + String(lowerBound);
  }else if(n < ((upperBound + lowerBound)/2)){
    return lowerBound;
  }else{
    return upperBound;
  }
}

Comments

@matheusml

raythree

added a commit
to raythree/react-slingshot
that referenced
this issue

Aug 15, 2017

@raythree

coryhouse

pushed a commit
to coryhouse/react-slingshot
that referenced
this issue

Aug 15, 2017

@raythree

@coryhouse

coryhouse

pushed a commit
to coryhouse/react-slingshot
that referenced
this issue

Sep 3, 2017

@TobiahRex

@coryhouse

* removed react-router form package.json & installed react-router-dom.

* completed index.src refactor.

* re-implemented App.js

* added notes to import changes & App.js

* modified middleware array @ store/configureStore.js

* updated yarn.lock file with fresh `yarn` command.

* updated master branch.

* upgraded react-hot-reloader to @3.0.0-beta.6

* removed extra "document.getElementById(app) from Root.js

* moved react-router-redux to regular "dependencies" from "dev-dependencies"

* cleaned Root.propTypes.

* cleaned Root.js & App.js per @oshalygin feedback.

* replaced .gitignore comment.

* removed react-router form package.json & installed react-router-dom.

* completed index.src refactor.

* re-implemented App.js

* added notes to import changes & App.js

* Update FAQ.md

fixed header on FAQ page

* Update README.md

fixed a few headers improperly declared

* modified middleware array @ store/configureStore.js

* Add react hot loader 3 (#392)

- This commit wires up react-hot-loader 3 to
  be used in the application.  There are numerous
  benefits to the latest release, all of which
  can be seen at https://github.com/gaearon/react-hot-loader
- Note that the specific implementation around
  wrapping in a Root component is part of how
  react-hot-loader 3 needs to be configured.
- Note that the package is brought in as a
  dependency, not a dev dependency because of
  how it is switched at runtime or not.
- More information on the migration can be
  viewed at:
https://github.com/gaearon/react-hot-loader/tree/master/docs#migration-to-30

Related: #216

* Updated react-hot-loader to correct package version. (#401)

* Add item to check if issues

* updated yarn.lock file with fresh `yarn` command.

* Fix formatting (#403)

* updated master branch.

* upgraded react-hot-reloader to @3.0.0-beta.6

* removed extra "document.getElementById(app) from Root.js

* moved react-router-redux to regular "dependencies" from "dev-dependencies"

* cleaned Root.js & App.js per @oshalygin feedback.

* replaced .gitignore comment.

* clean index.js

* Add CONTRIBUTE.md (#431)

* Add

* Updated yarn lock using upgrade

* Rename

* Update

* Upgrade to webpack 3

* Update yarn lock

* Update snapshot

* Set prod env when analyzing bundle

* Add jest-cli as dependency

* Revert PR #450 (#451)

Removed change that removed additional dashes in npm test scripts in favor of adding jest-cli as a devDep.

This commit instead focusses on issue 2 from #449 where setupPrompts.js had a bug that caused start script to fail.

* Issue #449 fix (#450)

* Issue #449 fix

Issue 1:
Removed extra dashes located in the package.json test scripts that cause start script to fail.

Issue 2:
Removed escape characters found in setupPrompts.js which cause linting to fail, thus breaking start script.

* Jest fix

Re-added previously removed dashes from test scripts in package.json that caused start script to fail. Instead, @coryhouse added in jest-cli as a dev-dep which resolves the issue.

* Enhance babel env config to transpile for IE9+ (#452)

* Fix for jest handling of static assets when running tests. See: (#457)

facebook/jest#2663 (comment)

* Added tips for npm run lint and build errors (#151) (#460)

* pushing changes from upstream fetch.

* updated from rebase.

* modified package versions in package.json & created new build.

* update package.json

* fixed conflicts with upstream master.

* cleaned up PropTypes validations - react-router-redux throwing PropTypes error.

* comment spell check & de-console on Root.js

This was referenced

Oct 19, 2018

newsum2019

added a commit
to newsum2019/singleshot
that referenced
this issue

Oct 6, 2019

@newsum2019

newsum2019

added a commit
to newsum2019/singleshot
that referenced
this issue

Oct 6, 2019

@newsum2019

* removed react-router form package.json & installed react-router-dom.

* completed index.src refactor.

* re-implemented App.js

* added notes to import changes & App.js

* modified middleware array @ store/configureStore.js

* updated yarn.lock file with fresh `yarn` command.

* updated master branch.

* upgraded react-hot-reloader to @3.0.0-beta.6

* removed extra "document.getElementById(app) from Root.js

* moved react-router-redux to regular "dependencies" from "dev-dependencies"

* cleaned Root.propTypes.

* cleaned Root.js & App.js per @oshalygin feedback.

* replaced .gitignore comment.

* removed react-router form package.json & installed react-router-dom.

* completed index.src refactor.

* re-implemented App.js

* added notes to import changes & App.js

* Update FAQ.md

fixed header on FAQ page

* Update README.md

fixed a few headers improperly declared

* modified middleware array @ store/configureStore.js

* Add react hot loader 3 (#392)

- This commit wires up react-hot-loader 3 to
  be used in the application.  There are numerous
  benefits to the latest release, all of which
  can be seen at https://github.com/gaearon/react-hot-loader
- Note that the specific implementation around
  wrapping in a Root component is part of how
  react-hot-loader 3 needs to be configured.
- Note that the package is brought in as a
  dependency, not a dev dependency because of
  how it is switched at runtime or not.
- More information on the migration can be
  viewed at:
https://github.com/gaearon/react-hot-loader/tree/master/docs#migration-to-30

Related: #216

* Updated react-hot-loader to correct package version. (#401)

* Add item to check if issues

* updated yarn.lock file with fresh `yarn` command.

* Fix formatting (#403)

* updated master branch.

* upgraded react-hot-reloader to @3.0.0-beta.6

* removed extra "document.getElementById(app) from Root.js

* moved react-router-redux to regular "dependencies" from "dev-dependencies"

* cleaned Root.js & App.js per @oshalygin feedback.

* replaced .gitignore comment.

* clean index.js

* Add CONTRIBUTE.md (#431)

* Add

* Updated yarn lock using upgrade

* Rename

* Update

* Upgrade to webpack 3

* Update yarn lock

* Update snapshot

* Set prod env when analyzing bundle

* Add jest-cli as dependency

* Revert PR #450 (#451)

Removed change that removed additional dashes in npm test scripts in favor of adding jest-cli as a devDep.

This commit instead focusses on issue 2 from #449 where setupPrompts.js had a bug that caused start script to fail.

* Issue #449 fix (#450)

* Issue #449 fix

Issue 1:
Removed extra dashes located in the package.json test scripts that cause start script to fail.

Issue 2:
Removed escape characters found in setupPrompts.js which cause linting to fail, thus breaking start script.

* Jest fix

Re-added previously removed dashes from test scripts in package.json that caused start script to fail. Instead, @coryhouse added in jest-cli as a dev-dep which resolves the issue.

* Enhance babel env config to transpile for IE9+ (#452)

* Fix for jest handling of static assets when running tests. See: (#457)

facebook/jest#2663 (comment)

* Added tips for npm run lint and build errors (#151) (#460)

* pushing changes from upstream fetch.

* updated from rebase.

* modified package versions in package.json & created new build.

* update package.json

* fixed conflicts with upstream master.

* cleaned up PropTypes validations - react-router-redux throwing PropTypes error.

* comment spell check & de-console on Root.js

dididy

pushed a commit
to Yapp-17th/Web_2_Client
that referenced
this issue

Nov 12, 2020

dididy

pushed a commit
to Yapp-17th/Web_2_Client
that referenced
this issue

Nov 12, 2020

@dididy

DoctorJohn

added a commit
to RESKUE/reskueapp
that referenced
this issue

May 6, 2021

@DoctorJohn

@github-actions
github-actions
bot

locked as resolved and limited conversation to collaborators

Jun 10, 2021

Рассмотрим решение одной из часто встречаемых в консоли браузера ошибок Java Script — Uncaught SyntaxError: Unexpected token

Проблема связана с тем, что браузер, исполняя код, не нашел то, что ожидал. В большинстве случаев ошибка связана с нехваткой парного элемента. К примеру, если есть открывающаяся кавычка «, то должна быть и закрывающая кавычка ». Это относится и к фигурным скобкам {, а так же к обычным скобкам (, квадратными [ и т.п. Если браузер видит открывающуюся фигурную скобку {, то логично, что для нее будет и закрывающаяся. Если же закрывающаяся скобка отсутствует, то мы увидим сообщение Unexpected token. Но небольшая проблема отладки состоит в том, что строка, указывающая на ошибку не всегда верна.

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

Сообщение в консоли Unexpected / связано с регулярными выражениями. В таком случае номер строки в консоли указан верно.

Сообщение в консоли Unexpected ; обычно вызвано символом «;» внутри литерала объекта или массива, или списка аргументов вызова функции. В таком случае номер строки в консоли указан верно.

Для наглядности можно рассмотреть следующий код:

SyntaxError

Консоль указывает на 23 строку, на ней мы видим фигурную скобку. Следующая закрывающая фигурная скобка находится на 27 строке. Но если посмотреть внимательнее, она относится к функции на 22 строке. Следовательно мы имеем открытую скобку на 23 строке, а закрывающая отсутствует. В итоге ошибка Uncaught SyntaxError: Unexpected token. Для решения ставим закрывающий элемент на 25 строке.

Итак, легко понять, что  Unexpected token на самом деле получается благодаря невнимательности или случайному удалению парного элемента. Как правило быстрее найти ошибку помогает правильное форматирование когда. 

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

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like other programming languages, JavaScript has define some proper programming rules. Not follow them throws an error.An unexpected token occurs if JavaScript code has a missing or extra character { like, ) + – var if-else var etc}. Unexpected token is similar to syntax error but more specific.Semicolon(;) in JavaScript plays a vital role while writing a programme.
    Usage: To understand this we should know JavaScript also has a particular syntax like in JavaScript are concluded by a semi-colon(;) and there are many rules like all spaces/tabs/newlines are considered whitespace. JavaScript code are parsed from left to right, it is a process in which the parser converts the statements and whitespace into unique elements.
     

    • Tokens: All the operator (+, -, if, else…) are reserved by the JavaScript engine.So, it cannot be used incorrectly .It cannot be used as part of variable names.
    • Line terminators: A JavaScript code should end with semi-colon(;).
    • Control characters: To control code, it is important to maintain braces({ }) in a code. It is also important to defines the scope of the code.
    • Comments: A line of code written after // is a comment. JavaScript ignores this line.
    • Whitespace: It is a tab/space in code.Changing it does not change the functionality of the code.

    Therefore JavaScript code is very sensitive to any typo error. These examples given below explain the ways that unexpected token can occur.
    Example 1: It was either expecting a parameter in myFunc(mycar, ) or not, .So it was enable to execute this code. 
     

    javascript

    <script>

    function multiple(number1, number2) {

        function myFunc(theObject) {

            theObject.make = 'Toyota';

        }

        var mycar = {

            make: 'BMW',

            model: 'Q8-7',

            year: 2005

        };

        var x, y;

        x = mycar.make;

        myFunc(mycar, );

        y = mycar.make;

    </script>

    Output: 
     

    Unexpected end of input

    Example 2: An unexpected token ‘, ‘occurs after i=0 which javascript cannot recognize.We can remove error here by removing extra. 
     

    javascript

    <script>

    for(i=0, ;i<10;i++)

    {

      document.writeln(i);

    }

    </script>

    Output: 
     

    expected expression, got ', '

    Example 3: An unexpected token ‘)’ occur after i++ which JavaScript cannot recognize.We can remove error here by removing extra ). 
     

    javascript

    <script>

    for(i=0;i<10;i++))

    {

      console.log(i);

    }

    </script>

    Output 
     

    expected expression, got ')'

    Example 4: At end of if’s body JavaScript was expecting braces “}” but instead it got an unexpected token else.If we put } at the end of the body of if. 
     

    javascript

    <script>

    var n = 10;

    if (n == 10) {

        console.log("TRUE");

        else {

            console.log("FALSE");

        }

    </script>

    Output 
     

    expected expression, got keyword 'else'

    Similarly, unnecessary use of any token will throw this type of error. We can remove this error by binding by following the programming rules of JavaScript.
     

    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии

    А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Invalid object name sql ошибка
  • Invalid normal index 3ds max ошибка