Asserts should not be used for validating any kind of user input data. They shouldn't be used for error checking either. Assert is the way to make debugging for a programmer easier in case tests fail. Also it is a way to make your code easier to understand.
Consider this example:
function calculateSomeCrazyFormula(a,b,c) {
var d = a+b+c;
....
k = (x + y)*2;
assert(k != 0);
l = d/k;
....
return x;
}
My formula by it's specification assures that k will never be 0. Here I used assert almost as a comment in my code. It does not validate the logic - it's completely the opposite. With asserts I validate if my implementation of that complex logic is correct. Later, when I come back to my code and see l = d/k
I won't get suspicious about what happens when k is 0, because I see my assert
there and understand that 0
should never happen.
Also, if there is an error somewhere and 0
does happen, you will usually see some deeper error. For example:
function otherFormula(a,b,c) {
var x = calculateSomeCrazyFormula(a,b,c);
var y = doSomeStuff(x);
var z = doOtherStuff(y);
return z;
}
Without asserts you will get the wrong result of this function. You will have no idea why you are receiving 0 when it should be 1. You will have to start debugging the code line by line and understanding what went wrong.
With asserts, however, you will instantly notice the "assertion failed" error and will instantly minimize the scope to look for the problem.
Asserts are useful in any programming language including Javascript, however they shouldn't be there in Live environment. Therefore, some postprocessor system should remove all of the asserts out of your code before the release.