JavaDeveloper
JavaDeveloper

Reputation: 5660

how to sequence parameters in javascript functions

I was writing a code in javascript.

colorMixer = function (redIntensity, blueIntensity, greenIntensity)

{
   // mix color
}

colorMixer(10, 8, 7) // means red = 10, blue = 8, green = 7

colorMixer(10, 8) // means red = 10, blue = 8

Question: How to specify red = 10, green = 8, and no value for blue (i dont intend 0 value for blue) I want scene where value for blue is unknown and DONT want to provide any value for blue.

Upvotes: 1

Views: 620

Answers (3)

Virus721
Virus721

Reputation: 8335

colorMixer(color) {
    var r = r in color ? color.r : DEFAULT_R,
        g = g in color ? color.g : DEFAULT_G,
        b = b in color ? color.b : DEFAULT_B;
}

colorMixer({r: 255, g: 127, b: 0});
colorMixer({g: 127, b: 0});
colorMixer({r: 255});

Edit actually what i wrote before my edit was wrong. If using a 0 for a channel, the default value would have been used as 0 evaluates to false.

Upvotes: 2

Brigand
Brigand

Reputation: 86260

You can pass null to the function.

colorMixer(10, null, 8);

Inside the function, you can check if null was passed.

colorMixer = function (redIntensity, blueIntensity, greenIntensity) {
    if (blueIntensity === null) { ... }
}

Note that the difference between == and === is important here.

x == null will also be true if a parameter wasn't passed, e.g., colorMixer(1, 2)

x === null requires that the value is null.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707736

Without changing the calling method or function definition, you can use undefined.

colorMixer(10, undefined, 8);

And, then test each parameter to see if it's undefined within the function to see if it was passed. You could also use null as the indicator that the parameter was not passed, but I prefer undefined because then you can just leave off trailing arguments you don't intend to pass and they will automatically be undefined.

But, if this is a regular occurence, you can change the parameters so they are passed in an object and the function can then examine exactly what was passed. This is more extensible because it works equally well no matter how many possible arguments there are:

colorMixer({red: 10, blue: 8});

Then, in the colorMixer function itself, you look at the properties on the passed object and you can see exactly what was and wasn't passed.

Upvotes: 4

Related Questions