Sobes.tech
Junior

What will be displayed in the console if you use this in console.log?

sobes.tech AI

Answer from AI

Depends on the call context of console.log and the strict mode of JavaScript ("use strict").

In the global context (outside functions and modules):

  • In non-strict mode ("use strict" is absent or declared inside a function): this will refer to the global object (window in browsers, global in Node.js).
  • In strict mode: this will be undefined.

Inside a function:

  • In non-strict mode: this will refer to the global object if the function is called as a regular function (myFunction()). If the function is called as a method of an object (myObject.myMethod()), this will refer to the object (myObject). If the function is used as a constructor (new MyClass()), this will refer to the new instance.
  • In strict mode: this will be undefined if the function is called as a regular function. In other cases (object method, constructor), behavior is the same as in non-strict mode.

Inside an arrow function (=>):

  • this is lexically inherited from the surrounding context. This means that the value of this inside an arrow function will be the same as in the outer regular function or in the global context where the arrow function was declared, regardless of how it is called. Arrow functions do not bind this to their own call context.

Example:

// Global context
console.log(this); // In browsers: Window, in Node.js: global (non-strict mode)
                    // In browsers: undefined, in Node.js: undefined (strict mode)

// Regular function
function showThisNonStrict() {
  console.log(this);
}

showThisNonStrict(); // In browsers: Window, in Node.js: global

function showThisStrict() {
  "use strict";
  console.log(this);
}

showThisStrict(); // undefined

const myObject = {
  methodNonStrict: function() {
    console.log(this);
  },
  methodStrict: function() {
    "use strict";
    console.log(this);
  }
};

myObject.methodNonStrict(); // myObject
myObject.methodStrict();   // myObject

// Arrow function
const arrowFunc = () => {
  console.log(this);
};

arrowFunc(); // In browsers: Window, in Node.js: global (inherits from the global context)

const myObjectWithArrow = {
  arrowMethod: () => {
    console.log(this);
  }
};

myObjectWithArrow.arrowMethod(); // In browsers: Window, in Node.js: global (inherits from the declaration context)