Michael
Michael

Reputation: 9402

How to force console.log to always print quotes around strings

In Chrome at least, if I encounter the following two statements, I get different output depending on the context of the argument.

console.log(1,"1") → 1 "1"
console.log("test","2") → test 2

This is causing me trouble because I'm trying to figure out at which point a variable (whose value is supposed to be 1) is getting assigned with a string ("1"). When I looked through the console output, I couldn't find it anywhere, only to discover console.log() is inconsistent in how it prints strings.

What do I need to do to force the output of console.log to correctly reflect both the value and type of each argument?

Upvotes: 1

Views: 2097

Answers (3)

Patrick
Patrick

Reputation: 3367

I suggest you to use typeof for a more robust solution. Consoles aren't to be trusted!

typeof "2" == 'string' // returns true 
typeof 2 == 'number' // returns true

Upvotes: 1

Alex MDC
Alex MDC

Reputation: 2456

You can force all arguments to be handled consistently by starting off the log with an empty string:

console.log("", 1, "1") → 1 1
console.log("", "test", "2") → test 2

Interestingly nodejs has the same logging behavior so it must be standard. The first argument of a console.log() supports varies format strings so it may be a weird consequence of that.

Upvotes: 3

Joe Enos
Joe Enos

Reputation: 40413

You can always build your own wrapper function - looks like console.log isn't necessarily consistent across browsers, but you can simplify it, maybe something like:

function console_log() {
    var output = "";
    if (arguments) {
        var i;
        for (i = 0; i < arguments.length; ++i) {
            if (i > 0) {
                output += " ";
            }
            if (arguments[i] && typeof arguments[i] === "string") {
                output += JSON.stringify(arguments[i]);
            } else {
                output += arguments[i];
            }
        }
    }
    console.log(output);
}

console_log("a", 1);
console_log(1, "a");

Of course, modify this to suit your needs.

Upvotes: 1

Related Questions