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.

3
  • 1
    stackoverflow.com/questions/25325221/… Commented Sep 24, 2018 at 11:10
  • And as to why it works as expected in that one case, see the discussion about hoisting here: stackoverflow.com/questions/7506844 Commented Sep 24, 2018 at 11:13
  • @Chris G Poorly document is the right phrase. Just wasted 3 hours looking for this variable and Googling an answer. Commented Sep 24, 2018 at 11:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.