Uncaught syntaxerror missing after argument list как исправить

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

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

❌ 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 badges526 silver badges528 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

143k95 gold badges408 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

6826 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,2831 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.3k19 gold badges224 silver badges227 bronze badges

missing ) after argument list javascript: In JavaScript, the “missing) after argument list” error occurs when we make a syntactic error when calling a function, such as forgetting to split its arguments by a comma. To resolve the error, ensure that any syntax errors in the arguments list of the function invocation are corrected.

Below are the examples where this “SyntaxError: missing ) after argument list” occurs.

Case#1: Forgetting to use comma(,) or ‘+’ to separate the values

// Solving SyntaxError: missing ) after argument list Error

// Here we forgot to use comma(,) or + to separate the values 
// while printing it on the console which leads to 
// SyntaxError: missing ) after argument list error
console.log('x' 'y'); 

Output:

console.log('x' 'y'); 
^^^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we forgot to use comma(,) or + to separate the values while printing it
on the console which leads to // SyntaxError: missing ) after argument list error

Case#2: Printing ${} without the template strings

// Here we are printing ${} without the template strings 
// on the console.
// Hence SyntaxError: missing ) after argument list
console.log('The Metadata is:' + ${string_data});

Output:

console.log('The Metadata is:' + ${string_data}); 
^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we are printing ${} without the template strings on the console leading to an error

Case#3: When there is no comma(,) between the arguments

// Here there is no comma(,) between arguments for separating them
// so, SyntaxError: missing ) after argument list occurs
mul(3 2);

Output:

mul(3 2); 
^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here there is no comma(,) between arguments for separating them.
so, SyntaxError: missing ) after argument list occurs

Case#4:

// Initialize the variables 
const EmpName = 'Nick';
const EmpId = 2354;
// Here there is no comma(,) between arguments
// so, SyntaxError: missing ) after argument list occurs
console.log(EmpName EmpId);

Output:

console.log(EmpName EmpId); 
^^^^^^^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Case#5: When we forgot to close the bracket ) while calling a function

// Here we forgot to close the bracket ) while calling a function
// Hence SyntaxError: missing ) after argument list occurs
console.log("x", "y"

Output:

console.log("x", "y" 
^^^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

In case#1, the”missing ) after argument list” error is produced when a comma or the addition operator (+) is not added between the parameters in a function.

To resolve the error, ensure that any syntax errors in the parameter list of your function calls are corrected.

// Here we are using '+' operator for separation
console.log('welcome to ' + ' Btechgeeks');

// Here we are using comma(,) to separate the arguments
console.log('Btechgeeks'.slice(0, 3)); 

Output:

welcome to Btechgeeks
Bte

Delimiting a string with backticks (“)

Missing after argument list javascript: If you have a string that contains both double and single quotes, use a template literal, which is a string delimited by backticks (“).

// This is WRONG approch
const gvn_string1 = 'They're playing';

// Write the string as here while using both double and single quotes
const gvn_string2 = "They're playing"

// Or we can also write in this way using backticks(``)
const gvn_string3 = `They're playing`

Because template literals enclose the string with backticks, we can use both single and double quotes in the string’s contents without getting errors or having to escape any single or double quotes.

Conclusion

  • To resolve the “missing) after argument list” problem, ensure that any syntax errors are corrected when calling functions.
  • When the function is invoked, the error is frequently issued if the function arguments are not separated by a comma or the addition operator.

Понравилась статья? Поделить с друзьями:
  • Uncaught syntaxerror invalid or unexpected token как исправить
  • Uncaught referenceerror require is not defined как исправить
  • Uncaught phpmailerexception smtp error data not accepted
  • Uncaught pdoexception could not find driver как исправить
  • Uncaught in promise error request failed with status code 500