0

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

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));
  • Excellent! I was stuck in R mode, where the default values are placed in the brackets of the variable declarations. – Sean Roulet Jan 15 at 13:25
  • 1
    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 – Rodrigo E. Principe Jan 15 at 16:51
  • what you mean is that if power is undefinded or null then it will always default to 2? – Sean Roulet Jan 15 at 18:38
  • yes, that is exactly what it means, both approaches – Rodrigo E. Principe Jan 16 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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