Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 296
aditya Avatar asked Oct 29 '11 23:10

aditya


1 Answers

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);     } } 
like image 153
Gabriele Petrioli Avatar answered Oct 02 '22 10:10

Gabriele Petrioli