Skip to content

Console.log(this) JavaScript | Example code

  • by

JavaScript console log() function is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.

Where this keyword refers to an object.this points to a particular object.

Console.log(this) JavaScript will print the file path. It also depends on how a function that includes the ‘this’ keyword is being called.

Console log this JavaScript

Simple example code.

<!DOCTYPE html>
<html>
  <body>
    <script>

      console.log(this);

   </script>

 </body>
 </html>

Output:

Console log this JavaScript

The following four rules apply this in order to know which object is referred to by this keyword.

  1. Global Scope
  2. Object’s Method
  3. call() or apply() method
  4. bind() method

If a function that includes the ‘this’ keyword, is called from the global scope then this will point to the window object.

  <script>

    var myVar = 100;

    function WhoIsThis() {
      var myVar = 200;

      console.log("myVar = " + myVar); 
      console.log("this.myVar = " + this.myVar); 
    }

    WhoIsThis();

  </script>

Output: myVar = 200

this.myVar = 100

Do comment if you have any doubts or suggestions on this JS console topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading