I have this bit of code:
var has_logger = (window.console && window.console.log);
if (has_logger) {
window.console.log(data);
}
has_logger, instead of being a boolean value, is actually initialised to a function object ( function log() { [native code] } )
My questions:
There is no need to test for the console.log in modern browsers, correct?
What is the proper way to initialize has_logger to a boolean value instead of a function object?
console. log() restricts your code to work in environments where window is the global object (or a property of the global object).
In JavaScript, the console is an object which provides access to the browser debugging console. We can open a console in web browser by using: Ctrl + Shift + I for windows and Command + Option + K for Mac. The console object provides us with several different methods, like : log() error()
The console object provides access to the browser's debugging console. The console object is a property of the window object.
If Firebug is not enabled, Firefox will throw an error if you don't check.
var has_logger = !!(window.console && window.console.log);
will always be Boolean.
Yes, that's a perfectly fine way to test, and yes you do have to test. Note that your has_logger variable actually ends up with a reference to the function, so you could turn it into a boolean using the double-bang as Amadan said.
Beware of IE9's odd behavior around console.log, though.
If you want your code to work in other JavaScript environments than browsers, though, you might use this:
has_logger = typeof console === "object" && console.log;
You can safely test the type of a free reference even if it's not defined. That will work in browsers (where you have window) and other environments (where you don't).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With