Why does the value of this keyword value is different on normal function vs calling the function using window object

35 Views Asked by At
"use strict"

function hello(){
console.log(this);
}

hello(); // undefined
window.hello(); // window object

I was trying to create a simple hello function to print the value of this keyword on strict mode. I get undefined on normal function call. When I call the function using the window object, the value of this keyword is window object.

Curios to know what is happening behind the scenes.

1

There are 1 best solutions below

0
Fernando Langaro On

In JavaScript, the value of this inside a function depends on how the function is called. The behavior you're observing with your hello function in strict mode illustrates some fundamental concepts of JavaScript's execution context and the this binding.

When you call hello() directly, you're invoking the function in a standalone manner, without explicitly setting a context object (without an object before the dot), in this case, ‘this’ defaults to the global object (window in browsers). However, in strict mode, this does not default to the global object.

Instead, it remains undefined to prevent accidental interactions with the global scope, which is a safer and more predictable behavior. That's why you see undefined printed in strict mode.