Home  >  Article  >  Web Front-end  >  Introduction to the console.assert() function in JavaScript

Introduction to the console.assert() function in JavaScript

高洛峰
高洛峰Original
2017-02-03 14:31:471676browse

In the development and maintenance process of JavaScript programs, Assert (assertion) is a good feature used to ensure the correctness of the program. On browsers with debugging tools, this feature can be achieved by calling console.assert(). For example, in the following code, the console.assert() statement ensures that the score variable value length of the cat object is 3:

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 that needs to be asserted. Normally it should be true; 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:

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 the error message:

Introduction to the console.assert() function in JavaScript

Browser support

console.assert() is better supported by browsers with debugging tools. All major browsers support this function. However, it is worth mentioning that Firefox itself does not support this function. The Firebug plug-in must be installed on Firefox to use console.assert().

For more articles related to the introduction of the console.assert() function in JavaScript, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn