Rohan Sharma
Rohan Sharma

Reputation: 326

Understanding console.log(console.log(object))

I am new to programming and js and I am trying to learn crux of javascript.

var obj1 = {
    name: 'rawn',
    fn: function() {
        console.log(this);
    }
};
console.log(obj1.fn());

When I output this I get the object(as expected) - {name: "rawn", fn: ƒ} and on another line I get - undefined. So my question is why and how do I get undefined?

My understanding is that, we are writing this line - console.log(obj1.fn()); as , console.log(console.log(this)), so how does javascript engine gives the result as undefined (what was put as undefined in the execution context)?

Upvotes: 1

Views: 229

Answers (2)

deceze
deceze

Reputation: 522083

console.log(obj1.fn()) and console.log(console.log(this)) are not equivalent at all, but they actually have the same result for the same reason: the inner function does not return anything. The return value of these functions is undefined. Which is what the outer console.log logs.

Upvotes: 2

Sid
Sid

Reputation: 4997

This is because of two reasons. First, in console.log(this); the context of this inside the fn function is the object itself. Hence it prints the guts of obj1.

Secondly, in console.log(obj1.fn());, you are actually calling the method which returns nothing. Instead if you say console.log(obj1.fn); it will return:

ƒ () { console.log(this); }

Hope this helps.

Upvotes: 1

Related Questions