Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is window.console && console.log?

 if (open_date) {
        open_date = get_date_from_string(open_date);
        window.console && console.log(open_date);
        window.console && console.log(cancel_until);

What is window.console && console.log ? Does it have to be in the code? Through this script does not work on IE (all version) --> IE runs javascript only after pressing F12

like image 810
user2018036 Avatar asked Jan 28 '13 11:01

user2018036


4 Answers

1.) What is window.console && console.log ?

console.log refers to the console object used for debugging. for firefox i use firebug for example.

but if the console is not available the script will crash. so window.console checks if the console object is there and if so it uses its log function to print out some debug information.

2.) Does it have to be in the code?

no, its only for debugging purpose

like image 88
Jakob Avatar answered Nov 20 '22 13:11

Jakob


window.console && console.log(open_date); 

The above code is just short for an if conditional statement. It doesn't have to be there. it is for debugging purposes. For most browsers, you can hit F-12 to open the browser debug console. Chrome has a debug console built in. Firefox has an extension called FireBug that you can use. Below is the equivalent statement without the '&&'.

if (window.console) console.log(open_date); 

I prefer to add the following code at the beginning of my javascript code so that I do not have to have these "if" statements all over the place. It really saves space and removes potential errors.

if (typeof console == "undefined") { window.console = {log: function() {}}; }

Jon Dvorak's comment above contains an elegant alternative way of doing this:

console = window.console || {log:function(){}}
like image 27
Abraham Avatar answered Nov 20 '22 12:11

Abraham


The rightside-expression will only get evaluated if the leftside-expression is truthy. Thats how the logical AND operator works.

Its basically short for

if( window.console ) {
    console.log( open_date );
}

As you might guess correctly, it's a common pattern for this case, because the console object might not be available on every browser (especially mobiles).

like image 17
jAndy Avatar answered Nov 20 '22 12:11

jAndy


Console.log is a logger for browser which logs the messages on browser console. EDIT: Console.log is not supported for lower versions of Internet Explorer

like image 1
Abhijeet Pawar Avatar answered Nov 20 '22 11:11

Abhijeet Pawar