0

Is there any reason why something like this would not work?

var classReplace = function(object, newClass, originalClass = "") {
    //do stuff
}

I keep getting a "Uncaught SyntaxError: Unexpected token = " error because I add in the

originalClass = "" 

part

6

3 Answers 3

2

You can check to see if originalClass was defined and if not then assign it "",

var classReplace = function(object, newClass, originalClass) {
 if( typeof(originalClass) === "undefined" ) originalClass = "";
 //do stuff
}
Sign up to request clarification or add additional context in comments.

Comments

1

As Pointy said, setting a default argument value in this way isn't possible in JavaScript,

You can, however, achieve similar results by checking if said argument is undefined, and if so, setting it equal to your desired default value:

var classReplace = function(object, newClass, originalClass) {
    if (originalClass === undefined) originalClass = "";
    //do stuff
}

Comments

0

While this doesn't exist in JS out of the box, I can think of two options in addition to the other answers, that actually mimick the feature you are looking for.

a. CoffeeScript

Among other cool features, CS supports default function values:

var classReplace = (object, newClass, originalClass = "") ->
console.log(originalClass)

Of course this just gets interpreted as:

var classReplace = function(object, newClass, originalClass) {
  if (originalClass == null) {
    originalClass = "";
  }
  return console.log(originalClass);
};

But still nice to have for readability, and like I said, CS has a lot of other cool features, may be worth a look.

b. Lo-Dash's partialRight method. (link)

usage:

var originalFunction = function(a,b) { return a + b; },
    functionWithDefaultValues = _.partialRight(originalFunction, 1, 2);

jsfiddle

notes:

  1. _.partial, for some reason, doesn't have the same behaviour.
  2. _.partialRight appends the values from the right, so in the above, the default value for b is 1.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.