63

console.log takes an unspecified number of arguments and dumps their content in a single line.

Is there a way I can write a function that passes arguments passed to it directly to console.log to maintain that behaviour? For example:

function log(){
    if(console){
        /* code here */
    }
}

This would not be the same as:

function log(){
    if(console){
        console.log(arguments);
    }
}

Since arguments is an array and console.log will dump the contents of that array. Nor will it be the same as:

function log(){
    if(console){
        for(i=0;i<arguments.length;console.log(arguments[i]),i++);
    }
}

Since that will print everything in different lines. The point is to maintain console.log's behaviour, but through a proxy function log.

+---

I was looking for a solution I could apply to all functions in the future (create a proxy for a function keeping the handling of arguments intact). If that can't be done however, I'll accept a console.log specific answer.

3 Answers 3

98

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);
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't work in Chrome/Safari. It throws an "Illegal invocation" error.
@aditya, updated code.. i was not using the correct context.. you need to pass console as the this argument to apply..
Just to point out, using this in your script will still cause errors in IE9 or older (or even IE10 if you're not using the <meta http-equiv="X-UA-Compatible" content="IE=edge" /> tag) breaking your script on your first call to log(); Instead of if(console) you should do if(typeof(console) !== 'undefined') which works in browsers new and old, including IE6-IE11.
Updated the answer to use typeof as @purefusion pointed out. There is no drawback
missing a { before console.log.apply
8

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={};}})());

Comments

4

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.

6 Comments

This doesn't work in Chrome/Safari. It works in Firebug, but looking for a cross-browser solution here.
args = []; for(i=0; i<arguments.length; i++) args.push(arguments[i]); console.log.apply(null,args); - try that.
Nope. Apparently, any call to console.log.apply throws an Illegal invocation error.
Okay, what if you try console.log(args.join('')); instead of console.log.apply in my last bit of code?
That wouldn't be what I want. If one does log({}), it'll say [object Object] and not the usual.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.