In the development and maintenance of JavaScript programs, Assert is a good feature to ensure the correctness of the program. In browsers with debugging tools, this feature can be implemented by calling console.assert(). For example, in the following code, the console.assert() statement ensures that the score variable value of the cat object is 3:
The code copy is as follows:
function cat(name, age, score){
this.name = name;
this.age = age;
this.score = score;
}
var c = new cat("miao", 2, [6,8,7]);
console.assert(c.score.length==3, "Assertion of score length failed");
In the console.assert() statement, the first parameter is the result of assert that needs to be performed, which should be true under normal circumstances; the second parameter is the error message printed on the console when an error occurs. For example, when the array length of the score variable in the above example is not 3:
The code copy is as follows:
function cat(name, age, score){
this.name = name;
this.age = age;
this.score = score;
}
var c = new cat("miao", 2, [6,8]);
console.assert(c.score.length==3, "Assertion of score length failed");
After the code is executed, the Firebug console will print an error message:
Browser support
console.assert() is better supported on browsers with debugging tools, and all major browsers support this function. However, it is worth mentioning that Firefox itself does not support this function. You must install the Firebug plugin to use console.assert() on Firefox.