Search code examples
javascriptdebuggingconsoleinstanceofconsole.log

Operator Instanceof gives different results in Console.log Concatenation


Well, For debugging, I use console.log often & it Outputs a message to the Web Console. But I don't know why I'm getting a different result with instanceof operator with concatenation.

 console.log("Hello "+"Code!!"); //Prints `Hello Code!!` - Correct
 console.log("Hello ","Code!!"); //Prints `Hello Code!!` - Correct
 console.log("Hello "+"Code!! : "+Math.PI); //Prints `Hello Code!! : 3.141592653589793` - Correct
 console.log("Result ",[] instanceof Array); //Prints `Result true` - Correct

But the below line gives output as false. Why it isn't Result true?

console.log("Result "+[] instanceof Array); //Prints `false` Why?

Solution

  • You need to separate the two instances...

    console.log("Result "+([] instanceof Array)); // Result true

    Because this is not an Array --> "Result "+[]

    When you use the comma, you separate the two, that is why it works.
    When you use +, it combines the two into a string, then checks if it is an Array