Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Unexpected token = in Google Chrome

I have a javascript function which accept an optional parameter. This works fine in Firefox, but in Google Chrome it shows:-

Uncaught SyntaxError: Unexpected token =

My Code,

function errorNotification(text = "Something went wrong!") {
  $.pnotify({
      title: 'Error',
      text: text,
      type: 'error'
  });
}

I have seen lot of similar questions but I can't realize my problem.

like image 939
Anshad Vattapoyil Avatar asked Oct 31 '13 05:10

Anshad Vattapoyil


People also ask

How do I fix unexpected token error?

As you write your JavaScript application, the unexpected token error always occurs because JavaScript expected a specific syntax that's not fulfilled by your current code. You can generally fix the error by removing or adding a specific JavaScript language symbol to your code.

What is uncaught SyntaxError unexpected token '<'?

The error Uncaught SyntaxError: Unexpected token < is most commonly caused by your site's code referring to an asset that is no longer available. Most commonly, this is due to a filename change in assets generated during your build.

What does uncaught SyntaxError invalid or unexpected token mean?

The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.

What is uncaught Syntax error unexpected identifier?

The "Uncaught SyntaxError: Unexpected identifier" error occurs for 2 main reasons: Misspelling a keyword, e.g. Let or Class instead of let and class . Having a typo in your code, e.g. a missing or extra comma, parenthesis, quote or bracket.


3 Answers

You are using a default parameter feature which is supported only by Firefox now.

function errorNotification(text) {
    text = text || "Something went wrong!";
    $.pnotify({
        title: 'Error',
        text: text,
        type: 'error'
    });
}
like image 77
Arun P Johny Avatar answered Oct 22 '22 15:10

Arun P Johny


Javascript does not allow you to pass default arguments like that. You need to assign the default internally to the function.

function errorNotification(text) {
  text || (text = "Something went wrong!");
  $.pnotify({
      title: 'Error',
      text: text,
      type: 'error'
  });
}
like image 35
Mike Edwards Avatar answered Oct 22 '22 16:10

Mike Edwards


Note: The other answers won't work if you have a boolean value that you want to default to true. That's because anything||true will always return true. Instead you should do something like:

function foo(bar){
  if(bar === undefined)
    bar = true;
  //rest of your function
}
like image 40
Shelvacu Avatar answered Oct 22 '22 15:10

Shelvacu