Search code examples
javascriptnode.jsdeclare

How to stop display of container when declaring an empty variable/object in js/node.js


const readline = require('readline');

x = [];

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  rl.close();
  console.log(answer);
  x.push(answer);
});

console.log(x);

Output:

What do you think of Node.js? []

I would like to declare an empty array without it displaying '[]' so that it would just say: "What do you think of Node.js?"


Solution

  • A quick way would just to check the array's length and pass what you want displayed

    //if it has any length display array as normal
    //otherwise just pass empty string
    console.log( x.length? x : "" );
    

    Another option is you could just join() the array elements which will give you an empty string for empty arrays, and a comma separated list for non-empty

    console.log(x.join())
    

    A final option would be to use a custom inspect function. console.log in the nodejs environment ultimately calls util.inspect, or similar native function, for objects. Because of this you can add a custom inspect function that allows you to return a string of what you want displayed for that object.

    So again you would just test the array's length return an empty string in the case of empty array or return what the util.inspect method would have original returned

    Array.prototype[util.inspect.custom] = function(){
      if(!this.length){
        return "";
      }
      //passe customInspect:false so the custom inspect method wont be called again
      return util.inspect(this,{customInspect:false});
    }
    

    Of course this method would effect all arrays being logged or inspected so use it only if you need to.