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.
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.
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.
The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.
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.
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'
});
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With