Search code examples
javascriptv8

Does the d8 shell's console.log support format specifiers?


d8 is a minimal shell for running JavaScript programs using V8. Does the implementation of console.log in d8 support format specifiers/characters? I tried to use a format specifier, and it printed the specifier and the variable value (as shown below).

d8> for (i = 0; i < 10; i++)  {console.log('Number is %d', i);}
Number is %d 0
Number is %d 1
Number is %d 2
Number is %d 3
Number is %d 4
Number is %d 5
Number is %d 6
Number is %d 7
Number is %d 8
Number is %d 9
undefined

I see a similar question here: https://github.com/nodejs/node/issues/10292 ... Any insight would be helpful.


Solution

  • As you can see from your experiment, d8 does not support format specifiers. It wouldn't want to support anything that's not legal JavaScript.

    Speaking of which: JavaScript has "template literals" since a while. So without placing any requirements on d8 or console.log, anywhere you have strings you can do:

    let i = 42;
    console.log(`Number is ${i}`);
    let just_a_string = `1 + 2 = ${1+2}`;
    console.log(just_a_string);
    console.assert(just_a_string === "1 + 2 == 3");
    

    If you were hoping for more advanced formatting, like C-style %5d, AFAIK you'll have to build that yourself. If you're interested in floating-point numbers, .toFixed and .toPrecision might be helpful.