Pass arguments to console.log as first class arguments via proxy function

Solution 1:

This should do it ..

function log() {
    if(typeof(console) !== 'undefined') {
        console.log.apply(console, arguments);
    }
}

Just adding another option (using the spread operator and the rest parameters - although arguments could be used directly with the spread)

function log(...args) {
    if(typeof(console) !== 'undefined') {
        console.log(...args);
    }
}

Solution 2:

There is a good example from the html5boilerplate code that wraps console.log in a similar way to make sure you don't disrupt any browsers that don't recognize it. It also adds a history and smoothes out any differences in the console.log implementation.

It was developed by Paul Irish and he has written up a post on it here.

I've pasted the relevant code below, here is a link to the file in the project: https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
    arguments.callee = arguments.callee.caller;
    var newarr = [].slice.call(arguments);
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};

// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}}((function(){try {console.log();return window.console;}catch(err){return window.console={};}})());

Solution 3:

Yes.

console.log.apply(null,arguments);

Although, you may need to loop through the arguments object and create a regular array from it, but apart from that that's how you do it.