Javascript function best practices

I am moving on to Basic Algorithm Scripting and I understand what is needed
to complete the basic pass of the exercise, but I want I really would like to know
is what is considered best practice in of algorithm writing in the real world.

Take for example the ‘Factorialize a Number’ algorithm…
This would satisfy the exercise requirements, but it could break.

function factorial(num) {

var factorial = num;
while (–num > 0) {
factorial *= num;
}
return factorial;
}

I would like to know what other considerations should I know in order to make
a function that doesn’t break. Some of the things I came up with are:

  1. What if function argument is non-numeric? Should it handle strings? objects?
  2. What if the argument is floating-point, or a negative value?
  3. Should it check for bounds? what are the maximum safe values

If you have other function definition considerations I would like to hear them,
Thank you for your reply.

If you write the function yourself. There is a high chance that you don’t have to worry about those stuff since you know what each parameter does.

In basic algorithm, you are training problem solving skills not so much as making a function compatible in every situation.

In software this is something you will have to put into consideration because the function is used by other people and not yourself.

I don’t worry about as much, if something do break, it will appear in the console. Unless you want to be picky and check everything. 12, “12”, “twelve”, “1 2”, 012 etc.

1 Like

It’s called “bullet-proofing.” – i.e. making sure your program/function doesn’t throw an exception and crash if fed some unexpected input, or give an answer if fed an invalid input.

The issues you’ve raised are valid and would be a good programming exercise, even just for your own personal gratification of knowing a job well done.

In the real world, even if your function won’t be used by 3rd-parties and it’s just you, it’s still a good idea to account for these edge cases or invalid inputs.

1 Like

Thanks for introducing me to a new term that I can use to find more information. I’m an old schooler as well. Coding since 1980.