1. What is console.log()?
Except for some very old browsers, most browsers today have their own debugging capabilities; even if they do not, they can be supplemented by installing plug-ins. For example, older versions of Firefox do not have built-in debugging tools, in which case you can add debugging capabilities by installing the Firebug plugin. On browsers with debugging capabilities, a member variable named console is registered in the window object, which refers to the console in the debugging tool. Information can be printed to the console by calling the log() function of the console object. For example, the following code will print "Sample log" to the console:
The above code can be abbreviated as:
code show as below:
console.log() can accept any string, number and JavaScript object. Similar to the alert() function, console.log() also accepts newlines \n and tabs \t. The debug information printed by the console.log() statement can be seen in the browser's debug console. The behavior of console.log() may be different in different browsers. This article mainly discusses the use of console.log() in Firebug.
2. Compatible with browsers without debug consoles
For older browsers lacking debug consoles, the console object in the window does not exist, so using the console.log() statement directly may cause errors (null pointer) inside the browser bug) and eventually crashes some older browsers. In order to solve this problem, you can define a console object artificially, and declare that the log function of the console object is an empty function; in this way, when the console.log() statement is executed, these old browsers will not do anything:
window.console = {log : function(){}};
}
However, in most cases, this compatibility work is unnecessary - debugging code such as console.log() should be removed from the final production code.
3. Using parameters
Similar to the alert() function, console.log() can also accept variables and concatenate them with other strings:
var name = "Bob";
console.log("The name is: " + name);
Unlike the alert() function, console.log() can also accept variables as parameters and pass them into strings. The specific syntax is consistent with the printf syntax in C language:
var people = "Alex";
var years = 42;
console.log("%s is %d years old.", people, years);
The execution result of the above code is: "Alex is 42 years old."
Fourth, using other log levels
In addition to console.log(), Firebug also supports a variety of different log levels: debug, info, warn, error. The following code will print these different log levels to the console:
console.log("Log level");
console.debug("Debug level");
console.info("Info level");
console.warn("Warn level");
console.error("Error level");
As you can see from the Firebug console, the colors and icons of the print information at different log levels are different; at the same time, you can select different log levels in the console to filter the information: