Меню

Uncaught syntaxerror missing after argument list ошибка

The JavaScript exception «missing ) after argument list» occurs when there is an error
with how a function is called. This might be a typo, a missing operator, or an unescaped
string.

Message

SyntaxError: missing ) after argument list (V8-based & Firefox)
SyntaxError: Unexpected identifier 'x'. Expected ')' to end an argument list. (Safari)

Error type

What went wrong?

There is an error with how a function is called. This might be a typo, a missing
operator, or an unescaped string, for example.

Examples

Because there is no «+» operator to concatenate the string, JavaScript expects the
argument for the log function to be just "PI: ". In that case,
it should be terminated by a closing parenthesis.

console.log('PI: ' Math.PI);
// SyntaxError: missing ) after argument list

You can correct the log call by adding the + operator:

console.log('PI: ' + Math.PI);
// "PI: 3.141592653589793"

Alternatively, you can consider using a template literal, or take advantage of the fact that console.log accepts multiple parameters:

console.log(`PI: ${Math.PI}`);
console.log('PI: ', Math.PI);

Unterminated strings

console.log('"Java" + "Script" = "' + 'Java' + 'Script");
// SyntaxError: missing ) after argument list

Here JavaScript thinks that you meant to have ); inside the string and
ignores it, and it ends up not knowing that you meant the ); to end the
function console.log. To fix this, we could put a' after the
«Script» string:

console.log('"Java" + "Script" = "' + 'Java' + 'Script"');
// '"Java" + "Script" = "JavaScript"'

See also

Ситуация: вы пишете код, всё как обычно, запускаете скрипт и получаете ошибку:

❌ Uncaught SyntaxError: missing ) after argument list

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

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

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

Пример: обработчик jQuery

jQuery('document').ready(function () {
  jQuery('button').on('click'.function(){
    var value1, value2 ;
    value1 = jQuery('#val1').val();
    value2 = jQuery('#val2').val();
    alert(value1 + value2);
});    
  
  });

При запуске браузер будет ругаться на строчку jQuery('button').on('click'.function(){ и выдавать ошибку Uncaught SyntaxError: missing ) after argument list.

Но дело не в скобке — у нас с ними всё в порядке. Дело в том, что в этом примере программист поставил точку после'click', хотя там нужна запятая. А если стоит точка, то браузер воспринимает function как свойство, пытается с ним разобраться, понимает, что это какое-то очень длинное свойство, которое не заканчивается закрывающей скобкой. Отсюда и просьба про скобку.

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

Что делать с ошибкой Uncaught SyntaxError: missing ) after argument list

Здесь сложно дать какую-то общую инструкцию, потому что каждый раз всё индивидуально и дело в нюансах, но мы попробуем.

  1. На всякий случай действительно проверьте, не потерялась ли у вас закрывающая скобка. Маловероятно, но всё-таки.
  2. Проверьте код на опечатки. Если пропустить букву в команде, то браузер может воспринимать её как новую функцию с кучей параметров, после которых должна всё-таки быть закрывающая скобка.
  3. Посмотрите, правильно ли вы используете параметры при вызове, нужны ли внутри точки, запятые или другие скобки.
  4. Если есть кавычки внутри кавычек — используйте разные кавычки для внутреннего и внешнего, например так: " Привет, это журнал 'Код' ".
  5. Посчитайте, все ли параметры вы передаёте при вызове. Возможно, вы пытаетесь передать в функцию что-то лишнее, например, три параметра вместо двух.

Попробуйте сами. Найдите ошибки в этих фрагментах кода:

$(document).ready(function () {
  $("#anim").parents().eq(1).hover(
    function () {
      $(this).addClass('animated bounce');
    },
    function () {
      $(this).removeClass('animated bounce');
    },
    function () {
      $(this).css('animation-duration', 3s);   // ❌ говорит, что тут ошибка
    });
});
$.each(elements, fucntion(index, val){  // ❌ говорит, что тут ошибка
  console.log(index);
  console.log(val);
});

I am getting the syntax error:

SyntaxError: missing ) after argument list

From this jQuery code:

$('#contentData').append(
  "<div class='media'><div class='media-body'><h4 class='media-heading'>" + 
  v.Name + "</h4><p>" + v.Description + "</p><a class='btn' href='" + 
  type + "'  onclick="(canLaunch('" + v.LibraryItemId + " '))">
  View &raquo;
  </a></div></div>")

What kinds of mistakes produce this Javascript Syntax error?

Eric Leschinski's user avatar

asked Sep 21, 2013 at 10:06

karthik's user avatar

1

You had a unescaped " in the onclick handler, escape it with "

$('#contentData').append("<div class='media'><div class='media-body'><h4 class='media-heading'>" + v.Name + "</h4><p>" + v.Description + "</p><a class='btn' href='" + type + "'  onclick="(canLaunch('" + v.LibraryItemId + " '))">View &raquo;</a></div></div>")

answered Sep 21, 2013 at 10:08

Arun P Johny's user avatar

Arun P JohnyArun P Johny

382k65 gold badges525 silver badges527 bronze badges

0

How to reproduce this error:

SyntaxError: missing ) after argument list

This code produces the error:

<html>
<body>
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){

  }
</script>
</body>
</html>

If you run this and look at the error output in firebug, you get this error. The empty function passed into ‘ready’ is not closed. Fix it like this:

<html>
<body>
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){

  });      //<-- notice the right parenthesis and semicolon
</script>
</body>
</html>

And then the Javascript is interpreted correctly.

answered Feb 27, 2014 at 18:02

Eric Leschinski's user avatar

Eric LeschinskiEric Leschinski

142k95 gold badges407 silver badges332 bronze badges

2

For me, once there was a mistake in spelling of function

For e.g. instead of

$(document).ready(function(){

});

I wrote

$(document).ready(funciton(){

});

So keep that also in check

answered Feb 20, 2017 at 6:30

Chaitanya Gadkari's user avatar

1

I faced the same issue in below scenario yesterday. However I fixed it as shown below. But it would be great if someone can explain me as to why this error was coming specifically in my case.

pasted content of index.ejs file that gave the error in the browser when I run my node file «app.js». It has a route «/blogs» that redirects to «index.ejs» file.

<%= include partials/header %>
<h1>Index Page</h1>
<% blogs.forEach(function(blog){ %>
    <div>
        <h2><%= blog.title %></h2>
        <image src="<%= blog.image %>">
        <span><%= blog.created %></span>
        <p><%= blog.body %></p>
    </div>
<% }) %>
<%= include partials/footer %>

The error that came on the browser :

SyntaxError: missing ) after argument list in /home/ubuntu/workspace/RESTful/RESTfulBlogApp/views/index.ejs while compiling ejs

How I fixed it : I removed «=» in the include statements at the top and the bottom and it worked fine.

Alex Kulinkovich's user avatar

answered Oct 25, 2018 at 4:31

utkarsh-k's user avatar

utkarsh-kutkarsh-k

6726 silver badges16 bronze badges

SyntaxError: missing ) after argument list.

the issue also may occur if you pass string directly without a single or double quote.

$('#contentData').append("<div class='media'><div class='media-body'><a class='btn' href='" + type + "'  onclick="(canLaunch(' + v.LibraryItemName +  '))">View &raquo;</a></div></div>").

so always keep the habit to pass in a quote like

 onclick="(canLaunch('' + v.LibraryItemName  + ''))"

answered Jan 31, 2020 at 5:01

Rinku Choudhary's user avatar

Rinku ChoudharyRinku Choudhary

1,2451 gold badge13 silver badges21 bronze badges

use:

my_function({width:12});

Instead of:

my_function(width:12);

answered Jan 20, 2015 at 13:01

T.Todua's user avatar

T.ToduaT.Todua

51.2k19 gold badges223 silver badges225 bronze badges

Labrador retriever puppy walking on green grass

Sometimes, we may run into the ‘SyntaxError: missing ) after argument list’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘SyntaxError: missing ) after argument list’ when we’re developing JavaScript apps.

Fix the ‘SyntaxError: missing ) after argument list’ When Developing JavaScript Apps

To fix the ‘SyntaxError: missing ) after argument list’ when we’re developing JavaScript apps, we should make sure we have corresponding closing parentheses for each opening parentheses in our JavaScript code.

On Edge, the error message for this error is SyntaxError: Expected ')'.

And on Firefox, the error message for this error is SyntaxError: missing ) after argument list.

For instance, if we write:

console.log('PI: ' Math.PI);

then the error will be thrown because we’re missing the comma between 'PI: ' and Math.PI.

To fix this, we write:

console.log('PI: ',  Math.PI);

The error will also be thrown if we have unterminated strings.

For instance, if we write:

console.log('"Java"' + 'Java' + 'Script");

then we’ll get the error since we don’t have a closing single quote in the 'Script" string.

To fix this, we write:

console.log('"Java"' + 'Java' + 'Script"');

Conclusion

To fix the ‘SyntaxError: missing ) after argument list’ when we’re developing JavaScript apps, we should make sure we have corresponding closing parentheses for each opening parentheses in our JavaScript code.

On Edge, the error message for this error is SyntaxError: Expected ')'.

And on Firefox, the error message for this error is SyntaxError: missing ) after argument list.

Web developer specializing in React, Vue, and front end development.

View Archive

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    This JavaScript exception missing ) after argument list occurs if there is an error in function calls. This could be a typing mistake, a missing operator, or an unescaped string.

    Message:

    SyntaxError: Expected ')' (Edge)
    SyntaxError: missing ) after argument list (Firefox)
    

    Error Type:

    SyntaxError
    

    Cause of Error: Somewhere in the code, there is an error with function calls. This could be either be a typing mistake, a missing operator, or an unescaped string.

    Example 1: In this example, there is a missing operator in string concatenation, So the error has occurred.

    HTML

    <!DOCTYPE html>

    <html>

    <head>

        <title>Syntax Error</title>

    </head>

    <body>

        <script>

            var str1 = 'This is ';

            var str2 = 'GeeksforGeeks';

            document.write(str1 str2);

        </script>

    </body>

    </html>

    Output(In console):

    SyntaxError: missing ) after argument list
    

    Example 2: In this example, there is a unescaped string, So the error has occurred.

    HTML

    <!DOCTYPE html>

    <html>

    <head>

        <title>Syntax Error</title>

    </head>

    <body>

        <script>

            var str1 = 'This is ';

            var str2 = 'GeeksforGeeks';

            document.write(str1 str2);

        </script>

    </body>

    </html>

    Output(in console):

    SyntaxError: missing ) after argument list
    

    SyntaxError: missing ) after argument list

    The JavaScript exception «missing ) after argument list» occurs when there is an error with how a function is called. This might be a typo, a missing operator, or an unescaped string.

    Message

    SyntaxError: missing ) after argument list (V8-based & Firefox)
    SyntaxError: Unexpected identifier 'x'. Expected ')' to end an argument list. (Safari)
    

    Error type

    What went wrong?

    There is an error with how a function is called. This might be a typo, a missing operator, or an unescaped string, for example.

    Examples

    Because there is no «+» operator to concatenate the string, JavaScript expects the argument for the log function to be just "PI: ". In that case, it should be terminated by a closing parenthesis.

    console.log('PI: ' Math.PI);
    
    

    You can correct the log call by adding the + operator:

    console.log('PI: ' + Math.PI);
    
    

    Alternatively, you can consider using a template literal, or take advantage of the fact that console.log accepts multiple parameters:

    console.log(`PI: ${Math.PI}`);
    console.log('PI: ', Math.PI);
    

    Unterminated strings

    console.log('"Java" + "Script" = "' + 'Java' + 'Script");
    
    

    Here JavaScript thinks that you meant to have ); inside the string and ignores it, and it ends up not knowing that you meant the ); to end the function console.log. To fix this, we could put a' after the «Script» string:

    console.log('"Java" + "Script" = "' + 'Java' + 'Script"');
    // '"Java" + "Script" = "JavaScript"'
    

    See also

    • Functions


    JavaScript

    SyntaxError: missing = in const declaration
    The JavaScript exception «missing const declaration» occurs when was not given value same statement (like RED_FLAG;).
    SyntaxError: missing name after . operator
    The JavaScript exception «missing name after The dot operator is used for property access.
    SyntaxError: missing ) after condition
    The JavaScript exception «missing after condition» occurs when there an error with how if written.
    SyntaxError: missing ; before statement
    The JavaScript exception «missing before statement» occurs when there semicolon somewhere and can’t added by automatic insertion (ASI).

    Добрый день, помогите решить проблему)

    Во фронте не силен, с горем пополам изначально настроил сборку для своего проекта, всё работало, сейчас решил пересобрать верстку и получаю ошибку:

    Error log

    PS D:.devdashboard> npm run dev
    
    > dashboard@1.0.0 dev D:.devdashboard
    > webpack --config webpack.dev.js
    
    D:.devdashboardnode_moduleswebpackbinwebpack.js:2
    basedir=$(dirname "$(echo "$0" | sed -e 's,\,/,g')")
              ^^^^^^^
    
    SyntaxError: missing ) after argument list
        at wrapSafe (internal/modules/cjs/loader.js:979:16)
        at Module._compile (internal/modules/cjs/loader.js:1027:27)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
        at Module.load (internal/modules/cjs/loader.js:928:32)
        at Function.Module._load (internal/modules/cjs/loader.js:769:14)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
        at internal/main/run_main_module.js:17:47
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! dashboard@1.0.0 dev: `webpack --config webpack.dev.js`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the dashboard@1.0.0 dev script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    Скрипты в package.json:

    scripts

    "scripts": {
        "test": "echo "Error: no test specified" && exit 1",
        "watch": "webpack --watch --config webpack.dev.js",
        "dev": "webpack --config webpack.dev.js",
        "prod": "cross-env NODE_ENV=production webpack --config webpack.prod.js"
      },

    При npm run prod точно такая же ошибка, только путь соответственно до cross-env.

    Не могу понять из-за чего это произошло, раньше все нормально работало.
    Пробовал на линуксе и на Windwos 10, аналогичная ошибка.
    Пробовал указывать полные пути node ./node_modules/webpack/bin/webpack.js вместо webpack, проблема не решилась(

    Популярные ошибки яваскрипта

    Подробности
    Категория: Javascript
    Просмотров: 3699

    Часто мелочевые ошибки при программировании на javascript рушат весь сайт. Самые популярные будем разбирать в этой статье…

    1.

    Ошибка Uncaught SyntaxError: Unexpected token ;

    Ошибка при программировании на javascript вида «Uncaught SyntaxError: Unexpected token ;» — возникает, когда вы поставили запятую лишнюю, найдите эту строчку и уберите запятую. (Переводится как — непредвиденная ошибка — то есть она как бы тут лишняя, и по правилам яваскрипта ее тут не предполагалось увидеть)

    2.

    Uncaught SyntaxError: missing ) after argument list

    Хитрая ошибка под названием «Uncaught SyntaxError: missing ) after argument list» — переводится, как «отсутствует скобка после аргумент листа». Но на самом деле вы может ищите скобку, а я вот разок просто опечатался, пример с JQuery:

    $.each(elements, fucntion(index, val){
                console.log(index);
                console.log(val);
            });

     Попробуйте найти ошибку сами) Нашли? Там лишь опечатка fucntion , а надо function — вот так вот)

    Добавить комментарий

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

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

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

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Uncaught in promise ошибка 403
  • Uncaught in promise ошибка 400