Search code examples
javascripttypechecking

try-catch encouraged instead of type checking in javascript?


In python, I've often heard that instead of checking the type of a variable to determine whether you want to do a certain operation on it, you should just wrap the operation in a Try statement and handle the Exception in case you have the wrong input type.

Is the same true of javascript? i.e. should one preferentially use a try / catch approach instead of typeof?


Solution

  • However lightweight is exception handling in any language, a rule of thumb is to always use exceptions for checking things that are exceptional.

    What I mean it's that if your algorithm needs type checking in normal operation, then it's better to check explicitly the typing using a condition, if the type checking is done to detect to detect abnormal operation, it's better to raise/handle an exception.

    Though, as Javascript is loosely typed, most of the time typing problems won't raise an exception, but instead work in a way that you do not always expect...