Domanda

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.

È stato utile?

Soluzione

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'
    });
}

Altri suggerimenti

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'
  });
}

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
}

function [a-zA-Z0-9_]*?\s{0,}\([^=$)]*?(=)[^)$]*?\) it can be helpful to find js functions with default parameter and then correct them.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top