Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Aug 2019
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Console Log Behaviour Question

    So if you console.log(object) it displays the entire object with a nice navigable tree in the browser (using the browser debug tools)... its really useful for debugging etc.... However if I write console.log("object=" + object), the output displays object=[Object object]. Does anyone know Javascript behaves this way?

  2. #2
    Master Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    5,846
    Thanks
    26
    Thanked 609 Times in 602 Posts
    Does anyone know Javascript behaves this way?
    that's correct behaviour. when you cast an object to string it displays as [<type> <constructor>]. cf. ECMAScript 2019 sec 19.1.3.6 (https://www.ecma-international.org/e...otype.tostring)
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  3. #3
    Senior Coder deathshadow's Avatar
    Join Date
    Feb 2016
    Location
    Keene, NH
    Posts
    3,605
    Thanks
    5
    Thanked 521 Times in 508 Posts
    To avoid this, use a comma instead of string addition. The various console output functions all support multiple input parameters, all treated as if they were one contiguous line in the output.

    console.log('object =', object);

    In general, if you can avoid string addition do so. This applies to console.log / console.warn / console.error and throw in JavaScript, as well as echo in PHP. Comma delimits in output commands execute faster, and won't accidentally perform typecasting on you.
    “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies.” – C.A.R. Hoare, The 1980 ACM Turing Award Lecture
    http://www.cutcodedown.com


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •