5

I am creating a user based function that I will save in my repository for re-use later. But I'm facing a problem with putting default values in my parameters.

var myFunction = function(number, power = 2){

return(ee.Number(a).pow(power);
}

print(myFunction(2);

print(myFunction(2,3);

The whole point is that most of the time I will want to square a number, but some time I may want to do another power. When you run the above example, you get an unexpected token error. Which is surely due to the "=" in the function definition.

How can I set default parameters?

1 Answer 1

7

You can do that easily using: Besides, yo have some missing brackets and you will have to use number inside the function where you places a.

var myFunction = function(number, power){

if (power === undefined || power === null){var power = 2}

return ee.Number(number).pow(power);
}

print(myFunction(2));

print(myFunction(2,3));
4
  • Excellent! I was stuck in R mode, where the default values are placed in the brackets of the variable declarations. Commented Jan 15, 2019 at 13:25
  • 3
    it could be simpler using power = power || 2 instead of if (power === undefined || power === null){var power = 2}, at least for checking undefined and null Commented Jan 15, 2019 at 16:51
  • what you mean is that if power is undefinded or null then it will always default to 2? Commented Jan 15, 2019 at 18:38
  • yes, that is exactly what it means, both approaches Commented Jan 16, 2019 at 10:24

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.