2

I'm totally confused about the behavior of console.log() when outputting a non-existing variable.

I was accidentally logging a non-existing variable bon. But the console didn't show "undefined" as expected, but <div id="bon">.

Searching where the variable was set (as I didn't set it and it had to be global, as it was popping up inside a function), I stripped all javascript, css and html untill there was nothing left at all:

<!DOCTYPE HTML>
<html> 
<head></head>
<body>
   <div id="bon">a</div>
   <script>
      console.log(bon);
   </script>
</body>
</html>

Testing in Firefox, Chrome, Explorer 11, Edge, Safari they all returned:

< div id="bon">

Changing the script into

<script>
    function foo(){
        console.log(bon);
    }
    foo();
</script>

gave the same result.

Only this

   <script>
      console.log(bon);
      var bon="not bon";
      console.log(bon);
   </script>

gave the expected output:

undefined
not bon

Am I missing something or does this mean the console just returns an element from the DOM with the same id if it can't find the variable itself?

Edit

As Chris G pointed out, the answer is found here. It turns out nowadays one can use id's to reference HTML elements in the global space without assigning them to a var=. But also: it is not recommended to do so.

Michel
  • 4,076
  • 4
  • 34
  • 52
  • 1
    https://stackoverflow.com/questions/25325221/why-dont-we-just-use-element-ids-as-identifiers-in-javascript –  Sep 24 '18 at 11:10
  • And as to why it works as expected in that one case, see the discussion about hoisting here: https://stackoverflow.com/questions/7506844 – Scott Sauyet Sep 24 '18 at 11:13
  • @Chris G _Poorly document_ is the right phrase. Just wasted 3 hours looking for this variable and Googling an answer. – Michel Sep 24 '18 at 11:25

1 Answers1

1

This is because you have a Div tag with the same ID and as "bon" has not been initiated anywhere in the Page. So "bon" automtically refers to the Div Tag.

Gopal M
  • 34
  • 4